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.