merlyn, I hate to critique code that was written on Christmas Eve, but this looks to have three separate bugs.
There are two major issues in the while(<>) loop. First, $_ plays a dual role in the inner for loop, with the looping value clobbering the data from the file. Adding an inner loop var (i.e. for my $key) will avoid clobbering $_.
The second bug involves the if qr/$hash_one{$_}[0]/ construct. This doesn't seem to be executing the regex, just compiling it (again??) and returning a true value. You can either drop the qr, leaving /$hash_one{$_}[0]/ or explicitly bind it with $_ =~ qr/$hash_one{$_}[0]/ or perhaps just $_ =~ $hash_one{$_}[0]
The third issue is more subtle, but still a bug. You aren't quoting special chars when compiling regexes for literal strings... qr/$_/ really should be qr/\Q$_\E/
With those three issues out of the way we have:
#!/usr/bin/perl -wT
use strict;
my %hash_one = ('string_one' => 0,
'string_two' => 0,
'[[[string_three' => 0, # test special chars behavio
+r
'string_four' => 0,
'string_five' => 0,
'string_six' => 0,
'string_seven' => 0);
# first, create an array ref, element 0 is a qr// of the key, and elem
+ent 1 is the count:
for (keys %hash_one) {
$hash_one{$_} = [qr/\Q$_\E/, 0];
}
# then walk the data, trying all the regexen:
# Replaced with <DATA> - blakem
# @ARGV = qw(file.txt);
# close ARGV;
while (<DATA>) {
for my $key (keys %hash_one) {
$hash_one{$key}[1]++ if $_ =~ $hash_one{$key}[0];
}
}
# finally, replace the arrayref with just the count:
$_ = $_->[1] for values %hash_one; # works in perl 5.5 and greater
print "$_ => $hash_one{$_}\n" for keys %hash_one;
__DATA__
1 string_one
string_two
2 string_two
[[[string_three
[[[string_three
3 [[[string_three
string_four
string_four
string_four
4 string_four
doesn'tmatchanything
Which works correctly and outputs:
string_four => 4
string_six => 0
string_five => 0
string_one => 1
string_seven => 0
[[[string_three => 3
string_two => 2
Those bugs make me think you coded that whole thing right here in the pm form box w/o running it through any sample data.... in a perverse sort of way, thats more impressive than if it had been totally clean the first time out. ;-)
-Blake
|