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.


True laziness is hard work

In reply to Re: anonymous subroutines assigning regexes to hash keys by GrandFather
in thread anonymous subroutines assigning regexes to hash keys by donkeykong

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.