Tim wrote in message news:1356726727.215915...@webmail.reagan.com...

I hope this is a simple fix.  I want to check the beginning characters of
items in a hash, and compare that to a scalar variable.
I do not need for the entire value to match; just the first couple of characters.
Tim


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
if ( $input_field =~ /$prefix_hash/ ) { print "$input_field is found in hash\n"; }
else { print "$input_field is not found\n"; }

#compare 03S to 03S and 04S
$input_field = "03S84844"; #should match
if ( $input_field =~ /$prefix_hash/ ) { print "$input_field is found in hash\n"; }
else { print "$input_field is not found\n"; }

Hello Tim,

If you had used strict it would have told you of the error. You should always
start your scripts with:

#!/usr/bin/perl
use strict;
use warnings;


There is no variable declared as: $prefix_hash. That is just a (undeclared) scalar
variable. You wanted the hash you created instead, I believe.

To use your hash, something like the following will produce the results
you want.


#!/usr/bin/perl
use strict;
use warnings;

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

#compare 05S to 03S and 04S
my $input_field = "05S885858"; #should not match
if ( $prefix_hash{ substr $input_field, 0, 3 } ) { print "$input_field is found in hash\n"; }
else { print "$input_field is not found\n"; }

#compare 03S to 03S and 04S
$input_field = "03S84844"; #should match
if ( $prefix_hash{ substr $input_field, 0, 3 } ) { print "$input_field is found in hash\n"; }
else { print "$input_field is not found\n"; }




I might have approached it differently.


#!/usr/bin/perl
use strict;
use warnings;

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

while (<DATA>) {
   print if /^$prefix_search_list/;
}

__DATA__
05S885858
03S84844
foo
bar
04Sbaz


*** prints

C:\Old_Data\perlp>perl t1.pl
03S84844
04Sbaz



Hope this helps,
Chris

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to