in reply to Re: Removing unwanted chars from filename.
in thread Removing unwanted chars from filename.
sub filter { my $str = shift or return ''; return $str =~ tr/A-Za-z0-9.-//cdr; }
The my $str = shift or return ''; statement will cause a file name of '0' to be converted to the empty string.
An alternative to avoid this problem is my ($str) = @_ or return '';
While such a file name seems unlikely to be encountered in the wild, it's best to be prepared. :)
Win8 Strawberry 5.30.3.1 (64) Thu 10/06/2022 19:03:53 C:\@Work\Perl\monks >perl use 5.014; # need /r modifier for tr/// use strict; use warnings; use Test::More; use Test::NoWarnings; my @Tests = ( [ q/xTest-1 [ ] 'copy'.png / => 'xTest-1copy.png', ], [ '0' => '0', ], [ '' => '', ], [ q/%^&*'{[(]})'.!@$/ => '.', ], [ q/%^&*'{[(]})'!@$/ => '', ], ); # end @Tests my @additional = qw(Test::NoWarnings emptylist); # each of these add +s 1 test plan 'tests' => (scalar grep { ref eq 'ARRAY' } @Tests) + @additional ; is filter(), '', "(empty list) -> ''"; # special case: empty argument + list VECTOR: for my $ar_vector (@Tests) { if (not ref $ar_vector) { note $ar_vector; next VECTOR; } my ($string, $expected) = @$ar_vector; my $got = filter($string); is $got, $expected, "'$string' -> '$expected'"; } # end for VECTOR sub filter { my ($str) = @_ or return ''; return $str =~ tr/A-Za-z0-9.-//cdr; } ^Z 1..7 ok 1 - (empty list) -> '' ok 2 - 'xTest-1 [ ] 'copy'.png ' -> 'xTest-1copy.png' ok 3 - '0' -> '0' ok 4 - '' -> '' ok 5 - '%^&*'{[(]})'.!@$' -> '.' ok 6 - '%^&*'{[(]})'!@$' -> '' ok 7 - no warnings
Give a man a fish: <%-{-{-{-<
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: Removing unwanted chars from filename.
by hippo (Archbishop) on Oct 07, 2022 at 09:22 UTC | |
by AnomalousMonk (Archbishop) on Oct 08, 2022 at 04:34 UTC |
In Section
Seekers of Perl Wisdom