in reply to Re: Mr. Ternary is greater than Mrs. If Else
in thread Mr. Ternary is greater than Mrs. If Else

The ampersand & marks the following { } construct as a code block; the backslash disambiguates that operation from binary '&' (the bitwise AND) and returns a reference for that code block.

It's not really a code block. \&{foo} is a reference to the subroutine with the name "foo". Similarly, \& { print "foo" } is a reference to the subroutine with the name that is returned by print, i. e. it's \&1 (unless print fails).

$ perl -lwe 'my $code = \&{print "foo"}' foo $ perl -lwe 'my $code = \&{print "foo"}; $code->()' foo Undefined subroutine &main::1 called at -e line 1.

(Note that $code is not called/dereferenced in the first one-liner, yet it prints foo.

Replies are listed 'Best First'.
Re^3: Mr. Ternary is greater than Mrs. If Else
by blazar (Canon) on May 20, 2007 at 14:03 UTC
    It's not really a code block. \&{foo} is a reference to the subroutine with the name "foo". Similarly, \& { print "foo" } is a reference to the subroutine with the name that is returned by print, i. e. it's \&1 (unless print fails).

    Well, there's a subtle difference. When you write &{foo} -with no quotes within the curlies-, that's (almost) just as if you had written &foo. This is not specific of subs, but of quite about all kind of variables:

    spock:~ [16:02:30]$ perl -wMstrict -le 'my $x=1; print ${x}' Ambiguous use of ${x} resolved to $x at -e line 1. 1 spock:~ [16:02:36]$ perl -wMstrict -le 'my $x=1; print ${"x"}' Can't use string ("x") as a SCALAR ref while "strict refs" in use at - +e line 1.