Search code examples
perlcpanhigher-order-functions

map(encode_entities, @_) does not seem to work


map(encode_entities, @_) does not seem to work, where the function is from HTML::Entities. I can work around it (see below), but is there a less ugly way? And could someone explain what is going on -- is there a conceptual error in my thinking?

use HTML::Entities;

sub foo {
    my @list = map(encode_entities, @_);
    return @list;
}

sub bar {
    my @list = @_;
    my $n = scalar @list;
    for my $k (0..$n-1) {
        $list[$k] = encode_entities($list[$k]);
    }
    return @list;
}

my @test = ('1 < 2', 'Hello world!');
print join("\n", bar(@test)); # prints the two lines, encoded as expected
print join("\n", foo(@test)); # undefined, gives "Use of uninitialized value..." error

Solution

  • There is no reason to assume that anything other than a Perl operator will use $_ as a default parameter: it would have to be written carefully to behave that way

    All you need to do is to call encode_entities with a specific parameter

    Try this

    sub baz {
        map encode_entities($_), @_;
    }
    

    It's likely that you will feel that a separate subroutine definition is unnecessary