in reply to call external sub ref from method in single line

>Welcome to the Monastery, previous! Thank you that's very kind of you. Additionally, thank you for the solution. That's a lot neater.
  • Comment on Re: call external sub ref from method in single line

Replies are listed 'Best First'.
Re^2: call external sub ref from method in single line
by AnomalousMonk (Archbishop) on Oct 05, 2015 at 13:34 UTC

    It's even possible to reduce the statement by two whole characters! — although I would argue that the code is de-clarified by doing so:

    c:\@Work\Perl\monks>perl -wMstrict -le "sub mysub { print 'hiya'; } my $hr = { sub_ref => \&mysub }; $hr->{sub_ref}(); " hiya


    Give a man a fish:  <%-{-{-{-<

        ... does a pair of parentheses () also count as a “subscript”?

        I've always assumed this is so and I've never encountered a counterexample, but this may just be because I almost always, if not always, use the
            $reference->{any}[$number]{of}[$levels]->();
        form; it seems more clear and the other form makes me just a bit nervous.

        Update: Perhaps my fondness for the form exemplified above has to do with the fact that I will often try to shorten and self-document my code by using intermediate variables:
            my $cr_that_does_something = $reference->{any}[$number]{of}[$levels];
            ...
            $cr_that_does_something->('foo');
            ...
            $cr_that_does_something->('bar');
        The  -> arrow is, of course, always needed here (if you don't use a sigil!).


        Give a man a fish:  <%-{-{-{-<

      Some golf code can have the advantage of clarifying the question by being read quickly. It may be more for quick examples because in production code spelling things out more may make for easier debugging and modification.

      It later occurred to me that you don't always need a subroutine reference to call outside an object or package although it could be useful. If the call is not object dependent you can just specify the name of the other package like "main::hello()".

      I included my simplified/golfed example below:

      package C; sub new { my $self = shift; my $class = ref($self) || $self; return bless {sub_ref => shift}, $class; } sub doit { $_[0]->{sub_ref}(); # you don't always need a reference to call outside of an object main::hello(); } package main; sub hello { print "hello\n"; } C->new(\&hello)->doit;
      Ron