in reply to Re: blocks and using braces around filehandles with print
in thread blocks and using braces around filehandles with print

The curlies are required when dealing with more complex expressions for the file handle.

Right, but what I want to know is: what exactly does that thing with the curlies around it evaluate to? I think the problem is, I don't really understand what a BLOCK is.

  • Comment on Re^2: blocks and using braces around filehandles with print

Replies are listed 'Best First'.
Re^3: blocks and using braces around filehandles with print
by dcd (Scribe) on Mar 16, 2008 at 22:49 UTC
    A block is 'code' in this case code that returns a file handle - see how perl deparse's the above code and puts a semicolon before the right curly brace in the code below:
    $ perl -MO=Deparse fh.pl
    die "Ouch. $!" unless open my $fh, '>', 'foo.txt'; print {$fh;} "hi!\n"; close $fh;
    fh.pl syntax OK
    (there are probably other methods that you can use to have perl show you what it is "thinking")
    perldoc -f print does mention the blocks
    Note that if you're storing FILEHANDLEs in an array, or if you're using any other expression more complex than a scalar variable to retrieve it, you will have to use a block returning the filehandle value instead: print { $files[$i] } "stuff\n"; print { $OK ? STDOUT : STDERR } "stuff\n";
Re^3: blocks and using braces around filehandles with print
by ikegami (Patriarch) on Mar 16, 2008 at 23:03 UTC

    A block contains 0 or more Perl statements. A block evaluates the the last value evaluated within the block.

    Examples:

    { STDOUT } -> STDOUT { $hash{$k}[$i] } -> $hash{$k}[$i] { my $x = func(); uc($x) } -> uc($x) { if ($cond) { 'FOO' } } -> If $cond is false, $cond. -> If $cond is true, 'FOO'.
      A block contains 0 or more Perl statements. A block evaluates the the last value evaluated within the block.

      If that's the case, then why doesn't the following work?

      #!/usr/bin/env perl use strict; use warnings; my $foo = { print "hi!\n"; my $bar = 7; my $baz = 8; }; print "So, \$foo = $foo\n";

        A block can only be used where a statement is expected, in a control flow statement where a block is expected, or as an operand to an operator that expects a block.

        Some operators that accept blocks:
        do BLOCK
        map BLOCK LIST
        print BLOCK LIST
        eval BLOCK

        In your code, do would perform what you want

        my $foo = do { print "hi!\n"; my $bar = 7; my $baz = 8; };