Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Perl's map with custom functions

I have a Perl script that has (skipping many irrelevant lines)

use HTML::Entities;
my @keys = ('ID', 'first', 'last'); # data is not actually constant
my @encodedKeys = map(encode_entities, @keys);

which runs without error. But when I try to access the values in the array, I get errors:

Use of uninitialized value $encodedKeys[0] in join or string at myfile.pl line 48.

If I remove the mapping the code works properly -- that is, the variables are not null or empty strings. What am I doing wrong? Is there a good idiomatic way to do this? (It's obviously trivial to do sequentially.)

like image 527
Charles Avatar asked Dec 31 '25 11:12

Charles


1 Answers

The encode_entities function does not use $_ by default, so you need to pass it an argument. Changing your map statement to the following will work:

my @encodedKeys = map {encode_entities $_} @keys
like image 109
Eric Strom Avatar answered Jan 02 '26 01:01

Eric Strom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!