in reply to Code explanation needed (was: What does this mean)

my @matches = grep { $file[$_] =~ /^\Q$storeline|\E/ } 0..$#file;
Loops through an array "file" pulling out array indexes which start with the string "$storeline|" (whatever storeline is) and set @matches to the result. This could be written as,
@matches = grep { /^\Q$storeline|\E/ } @file;
Calls the subroutine no_match passing $storeline as the arguement. returns if @matches is empty.
no_match($storeline), return unless @matches;
Calls the subroutine duped_ids passing $storeline as the arguement. returns if the number of elements in @matches is greater than 1.
duped_ids($storeline), return if @matches > 1;
</CODE>

Replies are listed 'Best First'.
Re: What does this mean
by Abigail-II (Bishop) on Jun 10, 2002 at 13:45 UTC
    Eh, no,
    my @matches = grep { $file[$_] =~ /^\Q$storeline|\E/ } 0..$#file;
    and
    my @matches = grep { /^\Q$storeline|\E/ } @file;
    are not equivalent. The former grabs the indices of where matches occur, while the latter grabs the matches themselves. Without knowing more about the rest of the program, I'm not going to say which version should be preferred.

    Abigail

      In Sifmole's defense, they are equivalent in the context of the code given. Since the values within @matches are never explicitly used, it doesn't matter precisely what is in there, just how many entries there are.

      This means, taking Sifmole's optimization one step further is possible:
      my $matches = grep { /^\Q$storeline|\E/ } @file; if ($matches > 1) { duped_ids($storeline); } elsif (!$matches) { no_match($storeline); } return;
      What I mean is that while technically they are not equivalent, in this particular sub-section of the program, they could be considered functionally equivalent.

      Admittedly, as you pointed out, there might be more code, but it's not posted here.
        Well, if you want to optimize, you better optimize, and stop matching as soon as you find a match. (Or one could argue that in the code given, neither duped_ids nor no_match are present, so we just optimize to the empty program).
        MATCH: { foreach (@file) { if (/^\Q$storeline|\E/) { duped_ids $storeline; last MATCH; } } no_match $storeline; }

        Abigail

      So right you are. My mistake.