Handling Context: an Example - Page 22
July 27, 2001
Putting all the above together, here is a final version of list_files that handles both scalar, list, and
void contexts, along with a sample program to test it out in each of the three contexts:
#!/usr/bin/perl
# listfile.pl
use warnings;
use strict;
sub list_files {
die "Function called in void context" unless defined wantarray;
my $path = shift;
return wantarray?():undef unless defined $path;
chomp $path;
# remove trailing linefeed, if present
$path.='/*' unless $path =~/\*/;
# add wildcard if missing
my @files = glob $path;
return wantarray?@files:\@files;
}
print "Enter Path: ";
my $path = <>;
# call subroutine in list context
print "Get files as list:\n";
my @files = list_files($path);
foreach (sort @files) {
print "\t$_\n";
}
# call subroutine in scalar context
print "Get files as scalar:\n";
my $files = list_files($path);
foreach (sort @{$files}) {
print "\t$_ \n";
}
# to get a count we must now do so explicitly with $#...
# note that 'scalar would not work, it forces scalar context.
my $count = $#{list_files($path)}+1;
print "Count: $count files\n";
# call subroutine void context - generates an error
list_files($path);
The name wantarray is something of a misnomer,
since there is no such thing as 'array context'. A better name
for it would have been wantlist.
Determining and Responding to the Calling Context - Page 21
Professional Perl Programming
Closures - Page 23
|