CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: Re: [rpaskudniak] wantarray returns 1 when function called in void context: Edit Log



2teez
Novice

Jul 28, 2013, 8:11 PM


Views: 5020
Re: [rpaskudniak] wantarray returns 1 when function called in void context

Hi,
I don't quite understand or get what you want to use your subroutine for. Though that been said, I think you are not really getting wantarray. Please do perldoc -f wantarray to see how to properly use it.
Suggestions:
1. Pass an array reference to your sub, then check if is an array ref, else the sub dies.
2. then using wantarray, return a list if your subroutine is called in a list context or a 'scalar' of the list generated within your sub, if the subroutine is called in a scalar context.
Like so:

Code
#!/usr/bin/perl -l 
use warnings;
use strict;


print realify( [qw(0.5 tim tolu 900_000)] );

my $an_val = realify( [qw(0.5 tim tolu 900_000)] );
print $an_val;

my @new_arr = qw(apple banana 1234 3.169);
my ( $red, $yellow, $num, $pi ) = realify( \@new_arr );
print $yellow;

my $pi_num = ( realify( \@new_arr ) )[3];
print $pi_num;

## I expect this to die
print realify(@new_arr);

## I also expect this to die
print realify(qw(apple banana 1234 3.169));

## I also expect this to die
print realify( 1 / 10 );

sub realify {
my ($val) = @_; ## or use shift.

die "You can only pass ARRAY reference"
unless ref $val eq 'ARRAY';

wantarray ? return @$val : return scalar @$val;
}


Please NOTE the context in which the subroutine is called.
NOTE: The script above is to illustrate the point mention, you might have to do much more to get what you wanted. Also note how, what is pass into the sub. was checked.
Using '$_[0]' like you did, might not be what you are really looking for.


(This post was edited by 2teez on Jul 28, 2013, 8:15 PM)


Edit Log:
Post edited by 2teez (Novice) on Jul 28, 2013, 8:12 PM
Post edited by 2teez (Novice) on Jul 28, 2013, 8:15 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives