Paul wrote:
> --- Rob Dixon <[EMAIL PROTECTED]> wrote:
> > Paul wrote:
> > > >     do {
> > > >         my $empty;
> > > >         $empty ++;
> > > >     };
> > >
> > > Also, the do() is superfluous here, isn't it?
> >
> > I was trying to show something that would return a value in
> > the same way as a subroutine block (so that I didn't need a
> > return statement in the same way as a subroutine doesn't).
> > I started out with a bare block, but realised that it needed
> > a 'do' to have a value, and therefore make it non-redundant
> > in context.
>
> Got it.
>
>   my $x = { code, more code.... }
>
> doesn't work, because the braces are expecting to be an anonymous hash
> in that context, so they aren't a block.
>
>   my $x = do { code };
>
> works, because do flips the context, expecting a block and returning a
> value.

I hadn't actually thought of it that way, but it's remarkably well
explained.
Well done.

> That way I can say
>
>   my $fh = do { local $_ };
>   open $fh, $file or die $!;
>
> for a cheap, quick, anonymous filehandle in a scalar. :)
> (note to the peanut gallery: henceforward I digress!)

Ah, now that's not quite right. The 'do' block will create a
local copy of $_, initialised to 'undef'. The end of the block
returns 'undef' as it is the last executed line, and $_ will
be restored from its saved value. The line is therefore the
same as:

    my $fh = undef;

or just

    my $fh;

and the entire code works as:

    open my $fh, $file or die $!;

> I've definitely used that trick...but all in all, for that
> *particular* usage I recommend
>
>   use FileHandle;
>   my $fh = new FileHandle $file or die $!;
>
> which is much more readable to the uninitiated, and still only two
> lines of code. ;o]

If we're counting lines, I think mine wins!

Rob




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to