I'm Perl beginner.I did not get why we use context(scalar,list,void)
in perl.
Please clarify my doubt with simple example.
I'm Perl beginner.I did not get why we use context(scalar,list,void)
in perl.
Please clarify my doubt with simple example.
An array is a list of contained values in list context, while number of contained values in scalar context. In void context, its value is thrown away.
$, = ' '; # printed fields will be delimited by spaces
my @arr = qw/a b c d/;
@arr; # nothing done (thrown away) in void context
print @arr, "\n"; # function arguments are evaluated in list context by default
print scalar(@arr), "\n"; # scalar() forces scalar context
“By default” refers to subroutine prototypes. See perlsub manual page (man perlsub
).
Output:
a b c d
4
Void context is not really interesting IMO. It is throwing the value away. If you call a subroutine returning a value without capturing that value (e.g. in a variable), it is called in void context. Notice that implicit return looks like not capturing the value, but in that case the context is inherited from the caller.
sub x {
return 42;
}
x(); # evaluated in void context
What one could view as interesting is that this generates no error, even though the subroutine returns something. Only when warnings are enabled, using constant or variable in void context generates warning.
In a subroutine, caller’s context can be determined using wantarray
. It returns undef
for void context, true for list context and false for scalar context. The expression in return’s argument is evaluated in this context.
sub print_context {
my $context = wantarray;
unless (defined $context) {
print "void\n";
} elsif ($context) {
print "list\n";
} else {
print "scalar\n";
}
return ''; # empty string
}
print_context(); # void
scalar(print_context()); # scalar
(print_context()); # void
print print_context(); # list
print (print_context()); # list
print +(print_context(), print_context()); # list twice
print scalar(print_context(), print_context()); # void, scalar (comma operator throws away its left operand’s value)
print scalar(+(print_context(), print_context())); # void, scalar (same as above)
print scalar(@{[print_context(), print_context()]}); # list twice, 2 once (array of two empty strings)
I must admit that scalar(print_context());
surprised me. I expected void.
More and more complicated artificial examples can be found.
The need to be aware of what context is comes from several practical problems though:
scalar()
or using one of the operators expecting scalars)=~
, ,
, <>
a.k.a. readline
, localtime
, reverse
, each
, caller
, …; and those user-defined using wantarray
, naturally)man perldata
).=
) determines the context for evaluation of the right one. Behavior of assignment operator depends on type of left operand.man perlsub
).return
’s argument is evaluated in the context inherited from caller.man perlop
).