Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Count the number of return values from a subroutine

by dkubb (Deacon)
on Jul 09, 2001 at 06:42 UTC ( [id://94891]=CUFP: print w/replies, xml ) Need Help??

This idiom gives you the number of return values from a subroutine. (Courtesy of P5P)
my $count = () = function(); print $count; # $count is '5' sub function { return qw(a b c d e); }

Replies are listed 'Best First'.
Re: Count the number of return values from a subroutine
by ariels (Curate) on Jul 09, 2001 at 16:07 UTC
    So do I, but $n = scalar foo does something completely different from $n = () = foo.

    Observe, I have nothing up my sleeve!

    sub foo { 5, 17 } # sub returning 2 values my $n1 = () = foo; # $n1 == 2 my $n2 = scalar foo; # $n2 == 17

    You forgot the general rule about converting a list to a scalar: "there is no general rule for converting a list to a scalar"!

Re: Count the number of return values from a subroutine
by particle (Vicar) on Jul 09, 2001 at 16:57 UTC
    i'd rather get the values as well, if possible.
    #!/usr/bin/perl -w use strict; $|++; use Data::Dumper; sub foo { [5, 3], 17 }; my $count = my (@values) = foo(); print $count, "\n"; print Dumper @values;
    puts out:
    2 $VAR1 = [ 5, 3 ]; $VAR2 = 17;
    but this line: my $count = my (@values) = foo(); is ugly, usually i'd declare the variables first.

    ~Particle

Re: Count the number of return values from a subroutine
by tomhukins (Curate) on Jul 09, 2001 at 15:58 UTC

      Your version won't produce the result you want if the function returns only one value: you'll just get the value returned.

      The p5p version works by filling a list with the return values and then assigning the list, not the function, to a scalar, and works equally well with one or more return values.

      It also allows you to keep the return values. This will give you a taste of what it's like maintaining my old code:

      sub splat { my @letters = split(/\s/,$_[0]); return (rand(2) > 1) ? @letters : \@letters; } my $count = my @letters = splat('The world is all that is the case.'); my $output = join(",",($count > 1) ? @letters : @{$letters[0]}); print $output;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-03-28 17:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found