Context of a Perl Subroutine
Published on 30 Nov 2007Tags #Perl
It is often useful to produce different return values depending on the context in which the subrouting or method was called, i.e. the type of return value that the caller expects:
#!/usr/bin/perl
use strict;
use warnings;
sub test {
if (not defined(wantarray)) {
die 'caller does not care for return value' . "n";
}
my @temp = (1, 2, 3, 4);
return wantarray ? @temp : "@temp";
}
my @test = &test();
print '@test: ' . join(' ', @test) . "n";
my $test = &test();
print '$test: ' . $test . "n";
&test();
Feedback is always welcome! If you'd like to get in touch with me concerning the contents of this article, please use Twitter.