Perl subroutines, context, and closures

Perl subroutines receive their arguments in the array @_ and usually copy them with my. Context is central to Perl: the same expression can behave differently in list and scalar context. A subroutine can ask for its caller's context with wantarray and return a list in one case and a single value in the other. An array in scalar context is its length, while assigned to a list it gives its elements.

Perl
use strict;
use warnings;

sub minmax {
    my @sorted = sort { $a <=> $b } @_;
    return wantarray ? ($sorted[0], $sorted[-1]) : "$sorted[0]..$sorted[-1]";
}
my ($min, $max) = minmax(4, 9, 2, 7);
my $range = minmax(4, 9, 2, 7);
print "$min $max $range\n";

sub counter {
    my $n = shift // 0;
    return { inc => sub { return ++$n }, get => sub { return $n } };
}
my $c1 = counter();
my $c2 = counter(10);
$c1->{inc}->() for 1 .. 3;
$c2->{inc}->();
print $c1->{get}->(), " ", $c2->{get}->(), "\n";

my $factorial;
$factorial = sub {
    my $n = shift;
    return $n <= 1 ? 1 : $n * $factorial->($n - 1);
};
print $factorial->(5), "\n";

my @list = (3, 1, 2);
my $count = @list;
my ($first) = @list;
print "$count $first\n";
Read the full lesson