in reply to Re: Anon. array of refs to a range generated list of scalars.
in thread Anon. array of refs to a range generated list of scalars.

I think the thing with the do {} syntax is that you aren't iterating with the do block.

You are iterating the do block itself.

For example:

$i=5; print do{ --$1 }; # prints 4 $i=5; print do{ --$i } while $i; # prints 43210

However, this is directly analogous to

$i=5; print --$1; # prints 4 $i=5; print --$i while $i; # prints 43210

In the latter example, its very clear that the while modifier form is iterating the print.

The former example, the while modifier is iterating the print also. It just so happens that the print has a do block as one of its terms. This is made clearer if you use the brackets on the print function like this.

$i=5; print( do{--$i;} ) while $i;

The confusion comes because we often format the construct like this

$i=5; do { print --$i; } while ($i);

Which makes it look like an iterate-at-least-once version of

$i = 5; while ($i) { print --$i; }

But you can show the difference by doing

my ($i, $j) = (5, 0); $j += do { print --$i; } while ($i); print $j; # prints 5.

Where the value 5 comes from the accumulation of the five 'successful' (1) return codes from the print function.

Additionally

If there is an inconsistancy with do, it's that the way it operates as an rvalue, makes it look somewhat analogous to the sort, map & grep functions, in as much as I half expected

print do( 'fred' ); to work like print do{ 'fred' } Somewhat like

 print map $_, 'fred'; is similar to print map{ $_ } 'fred';.

Actually, the error message from

 print do( 'fred' ); confuses me completly.


Examine what is said, not who speaks.

The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

Replies are listed 'Best First'.
Re3: Anon. array of refs to a range generated list of scalars.
by Hofmator (Curate) on Jan 18, 2003 at 19:38 UTC
    Actually, the error message from print do( 'fred' ); confuses me completly.
    What error message? You are aware of the different variants of do? From perldoc -f do
    do BLOCK [...] do SUBROUTINE(LIST) [...] do EXPR Uses the value of EXPR as a filename and executes the contents of the file as a Perl script.
    so probably the file named 'fred' doesn't exist and do returns simply undef - at least that's what it does here (on perl 5.6.0) generating thus a warning about Use of uninitialized value in print ...

    -- Hofmator

      Your right of course, I didn't think about the do EXPR; form at all.

      If I do print do('fred')|| warn $!;

      I get No such file or directory at ...


      Examine what is said, not who speaks.

      The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.