I'm trying to do something like
my %my_map = map { chomp($_) => 1 } @my_arr;
That doesn't do what I expect it to do, so I need to:
my @chomped_arr = @my_arr;
chomp @chomped_arr;
my %my_map = map { $_ => 1 } @chomped_arr;
What is the shorter way to do it?
The gotcha here is chomp modifies the variable, but doesn't return it. So it won't work in a map.
A workaround that I like is to use the r regex modifier -
my %my_map = map { s|\n||gr => 1 } @my_arr;
Which returns the modified result, but does so without altering the original (which would change @arr).
Note - the above doesn't quite chomp - it removes any linefeeds. (You can of course, stick a $ in your regex. e.g. s|\n$||r )
r regex flag is a newer feature (not that new). Can't recall OTOH which version of perl it was introduced in.
Can do it this with file handle input too :
my %stuff = map { s|\n||gr => 1 } <$fh>;
Strictly though, chomp removes $/ from the end of line so you might want
s|\Q$/\E\z||r
Which I think strictly reproduces chomp - but this might be a tradeoff of readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With