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

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

Replies are listed 'Best First'.
Re^2: What does this mean
by tadman (Prior) on Jun 10, 2002 at 14:08 UTC
    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

        "I love the smell of sarcasm in the morning. Smells like..." No wait, wrong Apocalypse.

        You can't optimize away function calls, since they're referenced, and so, clearly are present in some other place. That would be silly, but then, I'm sure that was the point.

        Remember that the condition was that duped_ids would be called on those lines that had > 1 number of entries, and it would appear that you are calling it here on the first.

        Also, call me crazy, but I despise labels. They're just not right. Maybe if you're programming in assembler, sure, you need labels, but in Perl? You can almost always avoid using them.
        my $found; foreach (@file) { if (/^\Q$storeline|\E/ && $found++) # First hit skipped { duped_ids($storeline); return; } } unless ($found) { no_match($storeline); return; }
        As they say in English: "Voila!"

        Now I'll admit I have a sneaking suspicion that somewhere else in the code there is some nonsense like foreach (@codes) { foo($_) } but I can't say for sure.
Re: Re: What does this mean
by Sifmole (Chaplain) on Jun 10, 2002 at 13:54 UTC
    So right you are. My mistake.