Search code examples
perl

Difference between calling named anonymous function and regular subroutine


I'm experimenting with anonymous functions in Perl, and I began to wonder what the difference between calling these two is:

my $read_file = sub {
    my ($filename) = @_;
    my @lines;
    
    open my $fh, '<:raw', $filename or die "Can't open file $filename: $!";
    while (my $line = <$fh>) {
        chomp $line;
        push @lines, $line;
    }
    close $fh;
    return @lines;
};

And this:

sub read_file {
    my ($filename) = @_;
    my @lines;
    
    open my $fh, '<:raw', $filename or die "Can't open file $filename: $!";
    while (my $line = <$fh>) {
        chomp $line;
        push @lines, $line;
    }
    close $fh;
    return @lines;
}

Solution

  • The biggest, and practically important, difference is that the named subroutine is created at compile time and is in the symbol table (global), while an anonymous one (a code reference) is created at runtime and is local to the scope in which it is created (and can be assigned to a lexical variable).

    So a code reference can be created and used within a scope and not be seen outside, like a "local" subroutine, it can be used for a closure, etc. A named subroutine cannot.

    But as for calling them, it's just subname(ARGS LIST) vs $coderef->(ARGS LIST).

    The phrase used in the question's title, "named anonymous" is a misnomer -- it is either named or anonymous (a code reference).


    In newer Perls we do have truly local subs, lexical (private) subroutines