in reply to {} vs do{}

The basic thing is: a BLOCK is not an EXPR(ession), but do BLOCK allows you to treat a BLOCK as an EXPR.

japhy -- Perl and Regex Hacker

Replies are listed 'Best First'.
Re: Re: {} vs do{}
by John M. Dlugosz (Monsignor) on Jul 04, 2001 at 21:14 UTC
    I see. In all the time I've been using Perl, I've sometimes run into times when I tried to use a block in an expression and it doesn't work. Putting do in front makes it work.

    Thanks for all the replies, everyone, this holiday.

    —John

      Just keep in mind the important caveat that:
      do { BLOCK } while ( COND );
      is NOT equivalent to:
      while ( COND ) { BLOCK }
      In the first case, the code in BLOCK is executed once before checking the condition. This goes for until as well. However:
      do { BLOCK } for ( LIST );
      is equivalent to:
      for ( LIST ) { BLOCK }
         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print
        The condition at the end running once before the test is something I've long known, since the Pascal days. That for doesn't is not something I've thought about.

        $value= "global"; do { print "Inside block: $value\n" } for (my $value= 5; $value < 7; ++$value);
        does not compile, so whether the loop variable is set first or later or what the scope is is moot. For the list form,
        $_= 1; do { print "Inside block: $_\n" } for (5..7);
        It is intuative that it work the same way, one iteration per item in the list, and you can't use a variable, e.g.
        do { print "Inside block: $value\n" } for my $value (5..7);
        doesn't compile either. So variable scope issues are avoided.

        Interesting.

        —John