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

Whats the best way to capture a line in an array from a smart match between an array and a scalar?
push @a, "aaa"; push @a, "bbb"; if ( @a =~ m/aa/) { #how do I print the line in @a that matches 'aa' #without going through the array. }
Thanks

Replies are listed 'Best First'.
Re: smart match capture
by davido (Cardinal) on Oct 13, 2011 at 15:18 UTC

    Yes, you can do that. You just have to use the appropriate special variables:

    use strict; use warnings; use v5.12; my @array = ( "First try this.", "Second try that.", "Third tried another.", "Fourth tried this last.", ); if( @array ~~ m/tried/p ) { say ${^PREMATCH} . ${^MATCH} . ${^POSTMATCH}; }

    The output is:

    Third tried another.

    So it appears that the smart match operator is smart enough to stop executing the test (in boolean context) as soon as the first successful match flips the conditional to true.

    Note the use of the /p modifier, to enable these lower-impact versions of $`, $&, and $'


    Dave

Re: smart match capture
by pvaldes (Chaplain) on Oct 13, 2011 at 13:35 UTC
    without going through the array

    mmmh, maybe "if exists"?

    If what you want is to stop the search after find the first aa, you could use "last".

      Unfortunately, from exists in perlfunc:
      Be aware that calling exists on array values is deprecated and likely +to be removed in a future version of Perl.
      Not sure what you mean by "last", that exits a block. Maybe you were thinking of first in List::Util?
      my $retn = first {m/aa/} @a;
      But that is not using the smart-match operator (~~ not =~)
Re: smart match capture
by Anonymous Monk on Oct 13, 2011 at 13:42 UTC