in reply to Re^4: regex question - dynamically address captures
in thread regex question - dynamically address captures

More readable:
sub get_captures { my ($pattern, $line) = @_; my @captures = $line =~ m/$pattern/; shift(@captures) if !$#+; return @captures; }
or
sub get_captures { my ($pattern, $line) = @_; my @captures = $line =~ m/($pattern)/; shift(@captures); return @captures; }

Replies are listed 'Best First'.
Re^6: regex question - dynamically address captures
by jkeenan1 (Deacon) on Jul 20, 2006 at 01:11 UTC
    The second example you showed ...

    sub get_captures { my ($pattern, $line) = @_; my @captures = $line =~ m/($pattern)/; shift(@captures); return @captures; }

    ... won't work in the production code of which my code presented here is a sample. That's because it would impose upon my users an unnecessary and likely-to-be-forgotten requirement: that they enclose the regex in parentheses so as to guarantee that at least one substring is captured.

    More interesting is this approach, which you tucked away:

    sub get_captures { my ($pattern, $line) = @_; my @captures = $line =~ m/$pattern/; return @captures[0 .. $#+ - 1]; }

    Once I understand @+ and @- better, I'll see whether I like this better than Grandfather's suggestion.

    Thank you very much.

    Jim Keenan