Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Count the number of return values from a subroutine

by dkubb (Deacon)
on Jul 09, 2001 at 06:42 UTC ( #94891=snippet: print w/replies, xml ) Need Help??
Description: 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: snippet [id://94891]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2022-12-09 02:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?