in reply to anonymous subroutines assigning regexes to hash keys
I really can't figure out what you think that code should do. However, if you add some data to the FILE block in the following code, then tell us what you expect to see as a result of running it, we may be able to get a handle on what you want to do.
use strict; use warnings; my $file = <<FILE; FILE open my $inFile, '<', \$file; my @ids = qw(1234 2345 3456); my %hash; foreach my $id (@ids) { while (<$inFile>) { $hash{$id} = { headline => sub { return /.*headline: (.*)/ }, byline => sub { return /.*byline: (.*)/}, }; } print $hash{$id}->{byline}->()."\n"; } close $inFile;
A few of the problems I see are:
1/ You open a file once outside a for loop, read to the end of the file on the first iteration of the loop, then want to read more stuff on subsequent iterations of the loop.
2/ Your anonymous subs use $_ for matching against, but $_ doesn't have a sensible value in the print where the sub might be called.
3/ Although you use strict, execution fails with 'Can't use string ("") as a subroutine ref while "strict refs" in use at ...'. Why didn't you mention this problem?
4/ Without strictures execution fails with 'Undefined subroutine &main:: called at ...'. Why didn't you tell us about this problem?
5/ You should always use the three parameter version of open and check the result.
|
|---|