rlk has asked for the wisdom of the Perl Monks concerning the following question:

I figured everone here is probably tired of hearing "why doesn't this work?", so I thought I'd ask "why does this work?" for a change.

In a recent node, I posted a piece of code similar to the following:

sub foo { print "In sub foo!" }; %bar = ( baz => \&foo ); $foo{baz}();

Now, this works, but btrott pointed out to me that $bar{baz} is a coderef, so the third line above should have been one of these two lines.

&{$bar{baz}}(); $bar{baz}->();

Now, both the Camel Book and perlref mention that the arrow operartor is optional between {}'s and []'s, (eg $foo{bar}->1->{baz} can be written as $foo{bar}1{baz})

However I can't find any documentation on automatic dereferencing of subroutine calls. Is this something that's lacking in the documentation, or am I missing something?

--
Ryan Koppenhaver, Aspiring Perl Hacker
"I ask for so little. Just fear me, love me, do as I say and I will be your slave."

Replies are listed 'Best First'.
RE: $foo{bar}-() vs. $foo{bar}()
by Carl-Joseph (Scribe) on Oct 07, 2000 at 10:58 UTC

    Evidently, this is a feature of Perl 5.6.

    Check out Camel3, page 283. The last two sentences of the section: Hashes of Functions.

    ". . . we invoke the appropriate command by derefencing the hash value as a function and pass that function and empty argument list. We could have dereferenced it as &{ $HoF{lc $cmd} }(), or, as of the 5.6 release of Perl, simply $HoF(lc $cmd}().

    Carl-Joseph

argh!
by rlk (Pilgrim) on Oct 07, 2000 at 11:00 UTC
    $above_post =~ s/[1]/[1]/g;
    -Ryan
      $above_post =~ s/\[1\]/\\[1\\]/;
      In other words, you forgot to escape the brackets, thus creating a character class. Of course, since the right side isn't a regex, it almost looks like we're substituting something back to itself. Weird.

      Sorry. Just couldn't resist :)

      Cheers,
      Ovid

      Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

      Point taken.
      -Ryan