Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^2: Removing unwanted chars from filename.

by AnomalousMonk (Archbishop)
on Oct 06, 2022 at 23:13 UTC ( [id://11147279]=note: print w/replies, xml ) Need Help??


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 (Bishop) on Oct 07, 2022 at 09:22 UTC

    Good catch! When composing my test I initially had that line as

    my $str = shift // '';

    but the idea of doing the rest of the processing (however swift) against the empty string rankled so I opted for the short-circuit instead. Should have just left it well alone :-)


    🦛

      First thought, best thought! :)


      Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11147279]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-03-29 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found