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

Is there any difference at all between given(...) and foreach(...) in 5.010? Or is it there just so that we slowly get more comfortable with Perl 6 syntax?

OOPS: Now I understand. given(...) considers a list as an array reference, and never loops. Is that right?

Replies are listed 'Best First'.
Re: given == for?
by moritz (Cardinal) on Jul 22, 2010 at 12:06 UTC
    You're correct. given aliases its argument to a lexicalized $_, but does no looping.
    Perl 6 - links to (nearly) everything that is Perl 6.
Re: given == for?
by LanX (Saint) on Jul 22, 2010 at 12:44 UTC
      Thanks. That is a much more detailed thread, and interesting. Perhaps you could post a summary of the conclusions reached by the end of that thread.
        Well, the first post already has the conclusions formulated as rhetoric question.

        Plz take a close look at the code examples, too!

        Most of the following thread is about underlying design decisions and mechanisms of the smart match operator (which is implicitly used in when).

        Cheers Rolf

Re: given == for?
by dave_the_m (Monsignor) on Jul 22, 2010 at 16:10 UTC
    for makes $_ an alias, given doesn't:
    $ perl5120 -wE'my $x=1; given ($x) { $_ = 2 } say $x' 1 $ perl5120 -wE'my $x=1; for ($x) { $_ = 2 } say $x' 2

    Edit: For some reason I wrote when rather than given above. Now fixed.

    Dave.

Re: given == for?
by JavaFan (Canon) on Jul 22, 2010 at 12:22 UTC
    Besides looping, foreach allows assigning the topic to a variable (foreach my $foo (...)), C-style loops (foreach (my $i = 0; $i < ...; $i++)) and its use a statement modifier. Furthermore, you cannot use a continue block, next, last or redo with given.

    At the moment, I can't think of anything given gives you that for/foreach doesn't.

      At the moment, I can't think of anything given gives you that for/foreach doesn't.

      Catching break.

      If you nest a for-loop and a given, you can selectively escape them with last and break.

      (OK, you can do that with labels too).

      Perl 6 - links to (nearly) everything that is Perl 6.
        If you nest a for-loop and a given, you can selectively escape them with last and break.

        (OK, you can do that with labels too).

        At least last allows labels - break doesn't.