Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Return a var from one sub to another

by Luken8r (Novice)
on Jul 10, 2007 at 20:26 UTC ( [id://625921]=perlquestion: print w/replies, xml ) Need Help??

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

Im a noob asking, what is likely a really noob question, so here it goes I have some code has some function foo() that I need to return two variables from to another function goo():
sub foo{ my %args = ( message => 0, error => 0); my $msg; my $var1 = 0 if ($var = 0) { $msg = "var 0"; return { error =>0, message=$msg } } else{ $msg = "not var 0" return { error =>1, message=$msg } }
What I would like to do is use error in some other function goo()
If I do
sub goo{ my $var = &file::foo(); system (`echo "var is $var" > ~/file`); }
I get some hash out of it. How can I get the individual variables error and message from the first function?

Replies are listed 'Best First'.
Re: Return a var from one sub to another
by philcrow (Priest) on Jul 10, 2007 at 20:29 UTC
    Your foo only returns one value which is a reference to a hash (which is a common technique). To get the values, use a bit more notation, something like so:
    sub goo { my $var = foo(); print "var is $var->{ message }\n" if $var->{error}; }
    The Gantry Web Framework Book is now available.
Re: Return a var from one sub to another
by FunkyMonk (Chancellor) on Jul 10, 2007 at 20:44 UTC
    You could use a hashref (which you're nearly doing):

    sub foo { #... return { errno => 0, errmess => $msg }; } my $error = foo(); print $error->{errno}, $error->{errmess};
    Or, you can use lists:

    sub foo { #... return ( 0, $msg ); } my ( $errno, $errmess ) = foo();

    Also, watch out for:

    if ($var = 0) {

    That's going to assign zero to $var. If you start all your scripts with:

    use strict; use warnings;

    perl will catch that for you (as well as many other errors & warnings).

    update: used parentheses instead of braces. doh.

      Thanks for the tips. Ill give that a shot

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://625921]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-24 12:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found