in reply to Mapping list to hash is dropping list items

perhaps - untested -:
#!/usr/bin/perl use strict; use warnings; use List::Util qw (uniq); # I think this is the fastest way for the trim functionality... # 2 statements benchmark faster than one statement sub myTrim { my $str = shift; #shift faster than @_ for one paramater $str =~ s/^\s*//; #no space at front $str =~ s/\s*$//; #no space at rear return $str; } my @fileTags = map{myTrim($_)}@fileTags. @fileTags = uniq @fileTags;
Update: I did run this:
Your Trim function does not trim the trailing spaces because the match (.*) is greedy...
#!/usr/bin/perl use strict; use warnings; use List::Util qw (uniq); sub myTrim { my ($str) = @_; my ($trimmed) = ($str =~ /\s*(.*)\s*/); return $trimmed; } my $x = "x "; $x = myTrim($x); print "$x!\n"; #prints "x !"
Update: The single statement version of your MyTrim() would be str =~ s/^\s*|\s*$//g; I saw one benchmark where that appeared to be faster than the "standard" 2 statements, but I was never able to re-create that result myself. Perl regex performance can vary significantly between releases - in general things get faster - but hiccups do happen.

Replies are listed 'Best First'.
Re^2: Mapping list to hash is dropping list items (trim whitespace)
by eyepopslikeamosquito (Archbishop) on Mar 13, 2022 at 12:06 UTC