Tanalis has asked for the wisdom of the Perl Monks concerning the following question:

Heys all,

I'm trying to grab information out of a series of files and place each file's data into an array of arrays for use later. Each file has a different number of pieces of information that I need to grab.

I'd like to do this using a foreach loop, iterating through each file, grabbing the data and assigning it to the array of arrays. I've defined an array of regular expressions, one for each file, that successfully grabs the data, however each regexp has a different number of strings to return.

What I'm wondering is how I can determine the number of returns ($1 .. $N) from a regexp, and return them, at run-time. Is there a variable somewhere that stores the number of matches, or do I need to store this myself (not a problem), and if so, is it legal to use code like

foreach ( 1 .. $numMatches ) { print $$numMatches }

to return each match?

Any comments or suggestions would be a great help.
-- Foxcub

Replies are listed 'Best First'.
Re: Returning N values from a Regexp
by thpfft (Chaplain) on Nov 13, 2002 at 13:15 UTC

    m// will return a list of matched (remembered) values if evaluated in list context. Your best bet would just be to gather the matches that way, then count them if you still need to.

    my $text = 'foxcub ' x 1000; my @matches = $text =~ m/fox(\w+)/g; my $count = scalar @matches; print join(', ', @matches);

    would print 'cub' 1000 times, in a comma-delimited list.

(z) Re: Returning N values from a Regexp
by zigdon (Deacon) on Nov 13, 2002 at 13:18 UTC
    Look in perlvar at @+ - ... You can use $#+ to determine how many subgroups were in the last successful match.

    -- Dan

Re: Returning N values from a Regexp
by diotalevi (Canon) on Nov 13, 2002 at 14:17 UTC

    I saw tye do this in the CB the other day - tre-cool. $count = () = /regex/g.

    __SIG__ use B; printf "You are here %08x\n", unpack "L!", unpack "P4", pack "L!", B::svref_2object(sub{})->OUTSIDE;
Re: Returning N values from a Regexp
by robartes (Priest) on Nov 13, 2002 at 13:02 UTC
    How about you store the return value of the regexp in an array list context and use the length of that array the returned list as $numMatches?

    CU
    Robartes-

    Update: clarified a bit.