Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

RE: Re: scalar doesn't work values returned by a function?

by perlmonkey (Hermit)
on May 11, 2000 at 11:08 UTC ( [id://11135]=note: print w/replies, xml ) Need Help??


in reply to Re: scalar doesn't work values returned by a function?
in thread scalar doesn't work values returned by a function?

I think you might be missing one of the finer points of perl.

Functions can return completly different value depending on what context they are called in. sort does not always return a list, it usually does. If sort is called is a scalar context then the function returns undef. It does not return a list if called in scalar context. So the scalar function is not placing the return value of sort in scalar context it is placing the the actual function call in scalar context.

Here is some code for demonstration:
This is what Russ was refering to
$scalar = (5,10,15,20); print $scalar, "\n";
Results:
20


This creates a function which will return different values depending on the context that the function was called in:
sub get_list { # return a list if a list is wanted, else # return the string return wantarray ? (5,10,15,20) : "SCALAR CALL"; }
And to see this code in action:
$scalar = get_list(); print $scalar, "\n"; @array = get_list(); print join(" ", @array), "\n";
Results:
SCALAR CALL
5 10 15 20


And similarly:
print scalar(get_list()), "\n"; print join(" ", get_list()), "\n";
Results:
SCALAR CALL
5 10 15 20


Hopefully this helps.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-19 15:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found