Context of a Perl Subroutine

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:


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";
Feedback is always welcome! If you'd like to get in touch with me concerning the contents of this article, please use Twitter.