in reply to Vexing views of variables

#!/usr/bin/perl -w use strict; { my $v = 1; sub mk_view_v { $v; ## <<< this is an error sub { $v }; #<<<this is a no op ?? #anon sub declaration that if called #would return $v ## but if $v is 1; then mk_view_v() returns 1; ## well maybe not, maybe this is supposed to ## return a ref to the anon sub{}? ## this still looks strange to me # weird } } print "(", mk_view_v()->(), ")\n"; # very strange print statement
prints (1), as one would expect.

I would like someone to walk me thru how
mk_view_v()->() generates the expected "1"!!!

I find the above code bizarre.
What this ->() is supposed to call the anon sub within mk_view_v()?

Replies are listed 'Best First'.
Re^2: Vexing views of variables
by JadeNB (Chaplain) on Aug 07, 2009 at 19:46 UTC
    The void-context $v is not an error, but it does generate a warning, which I didn't notice because I was naughty and didn't use warnings for my test script. Changing it to { no warnings 'void'; $v; } silences the warning (by brute force) and has the same effect.

    sub { $v } would normally be a no-op, but, here, it's the last line statement of a function definition, so it carries an implicit return. Thus, mk_view_v() returns that anonymous sub, and we call it as we would any other coderef.

    UPDATE: I should have said that the sub { $v } line carries 2 implicit returns—more explicitly, it's return sub { return $v }.