Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Returning Values from Subroutines

by mojobozo (Monk)
on Sep 06, 2002 at 14:51 UTC ( #195660=note: print w/ replies, xml ) Need Help??

in reply to Returning Values from Subroutines

Hey there. I'm not entirely sure why it's not working as is as I am but a novice, but the following works for me:

#!/usr/local/bin/perl my $answer = &add(1,2); print $answer; sub add{ return $result = ($_[0] + $_[1]); }

As far as the original not working, will the initial sub ("main") even run without a call to it? I tried running it with a call for it and got an error. Also, in the the "add" sub, you are returning $answer, but it was never assigned a value in the sub.

Anyone else want to chime in? I'd like to hear more on this one as well.


was hoping to get first return, but was beat out by six minutes... curses!

Comment on Re: Returning Values from Subroutines
Download Code
Replies are listed 'Best First'.
Re: Re: Returning Values from Subroutines
by mojobozo (Monk) on Sep 06, 2002 at 15:05 UTC
    A little more golf on this one:
    #!/usr/local/bin/perl print add(1,2); sub add{ return $result = ($_[0] + $_[1]); }

    Unless, of course, you wanted to save the value returned.
      And, using the example in ignatz's reposnse, even more strokes shaved:
      #!/usr/local/bin/perl print add(1,2); sub add{ return ($_[0] + $_[1]); }

      Man, this is getting fun. I wish I could shave this many strokes of my discgolf game!
      word (wrd)
      interj. Slang. Used to express approval or an affirmative response to
      something. Sometimes used with up. Source
        Well, as long as we're golfing:
        #!/usr/local/bin/perl print add(1,2); sub add{ $_[0] + $_[1]; }

        -- Dan

        The return keyword can be omitted when it's the last line of a sub, so this will also work:
        #!/usr/local/bin/perl print add(1,2); sub add{ $_[0]+$_[1]; }
        or for that matter
        sub add{ shift+shift; }
        Update: OK, so I guess the shift() there is ambiguous. Anyway, you get the point.


      In 9 strokes:

      # 123456789 sub add{pop()+pop}

      — Arien

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://195660]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (10)
As of 2015-11-25 14:50 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (679 votes), past polls