Thank you Tim.  The lack of strict and warnings should have been the first
thing that I put in the code.  Thank you for the correction and for the help
in the loop.

 

From: timothy adigun [mailto:2teezp...@gmail.com] 
Sent: Friday, December 28, 2012 4:11 PM
To: twle...@reagan.com
Cc: beginners@perl.org
Subject: Re: Pattern matching to hash

 

Hi,

 


my $prefix_search_list = '03S,04S';
my @prefix_array = split /\,/,$prefix_search_list;
my %prefix_hash = map {$_ => 1 } @prefix_array;

#compare 05S to 03S and 04S
my $input_field = "05S885858"; #should not match

 

  1. using stricts and warnings pragma, shows clearly that there is nothing
like the scalar variable "$prefix_hash". You only have a hash variable with
the name "%prefix_hash". Am sure you will appreciate why one would ask that
such pragma been turned ON. 

 

   2. Using, a "for or foreach" loop, one could compare each of the hash key
with the $input_field. like so:

 

#compare 05S to 03S and 04S

my $input_field = "05S885858";    #should not match

foreach my $prefix_match ( keys %prefix_hash ) {

    if ( $input_field =~ /$prefix_match/ ) {

        print "$input_field is found in hash\n";

    }

    else { print "$input_field is not found\n"; }

}

 

#compare 03S to 03S and 04S

foreach my $prefix_match ( keys %prefix_hash ) {

    $input_field = "03S84844";    #should match

    if ( $input_field =~ /$prefix_match/ ) {

        print "$input_field is found in hash\n";

    }

    else { print "$input_field is not found\n"; }

}

 

Below is the full script:

 

use warnings;

use strict;

 

my $prefix_search_list = '03S,04S';

my @prefix_array       = split /\,/, $prefix_search_list;

my %prefix_hash        = map { $_ => 1 } @prefix_array;

 

#compare 05S to 03S and 04S

my $input_field = "05S885858";    #should not match

foreach my $prefix_match ( keys %prefix_hash ) {

    if ( $input_field =~ /$prefix_match/ ) {

        print "$input_field is found in hash\n";

    }

    else { print "$input_field is not found\n"; }

}

 

#compare 03S to 03S and 04S

foreach my $prefix_match ( keys %prefix_hash ) {

    $input_field = "03S84844";    #should match

    if ( $input_field =~ /$prefix_match/ ) {

        print "$input_field is found in hash\n";

    }

    else { print "$input_field is not found\n"; }

}

 


Hope this helps.


 

-- 
Tim

Reply via email to