Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Determining subroutine return type

by Roy Johnson (Monsignor)
on Feb 24, 2005 at 22:39 UTC ( [id://434286]=note: print w/replies, xml ) Need Help??


in reply to Determining subroutine return type

if the subroutine returns a list I don't want to evaluate it in scalar context and end up with the length.
You wouldn't. You'd get the last element of the list. Not that that's much preferable. If you assigned the results to a list containing one scalar, you'd get the first. You'd have to do the $bar = () = foo trick to get the length.
my $foo = sub { return (4,5,8) }; # evaluate in (too-short) list context: my ($bar) = &$foo; print "Bar=$bar\n"; # evaluate in scalar context: $bar = &$foo; print "Bar=$bar\n"; # array context, sort of $bar = () = &$foo; print "Bar=$bar\n";

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Determining subroutine return type
by sandfly (Beadle) on Feb 24, 2005 at 23:16 UTC
    Subs returning arrays behave differently to subs returning lists. If your sub returns an array, calling it in scalar context gets you the number of elements. In list context there's no difference.
    perl -le "@a=(2,4,6); sub x{@a} print scalar(x());"
    prints 3, not 6.

Log In?
Username:
Password:

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

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

    No recent polls found