5% assure discount from here only

Tuesday, July 5, 2011

(29) What is wantarray in perl?

Solution:

wantarray is a special keyword which returns a flag indicating which context your subroutine has been called in.

It will return one of three values.

true: If your subroutine has been called in list context
false: If your subroutine has been called in scalar context
undef: If your subroutine has been called in void context

For example:-

You have a subroutine named "display" and from that subroutine sometimes you want to return an array and sometimes a scalar.

So the syntax would be

sub display(){
return(wantarray() ? qw(A B C) : '1');
}

my @ab = display();
my $bd = display();

then output is

#@ab = (A B C);
and
#$bd = 1;

The output will be depend upon the left hand side
assignment. If you put an array (@ab) it will call
wantarray() else a scalar value will return.

2 comments:

  1. "wantarray is a special keyword which return an array if executing function is looking for a list"

    No. wantarray will never return an array. It returns a flag indicating which context your subroutine has been called in. It will return one of three values.

    true: If your subroutine has been called in list context
    false: If your subroutine has been called in scalar context
    undef: If your subroutine has been called in void context

    Your example, works, but your explanation is confused and confusing.

    It's also worth noting that "wantarray" is badly named as Perl doesn't have an "array context". It should probably have been called "wantlist".

    ReplyDelete
  2. Thnx Dave for correcting me... It is always pleasure to learn things from people like you. :)

    ReplyDelete