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:  <%-{-{-{-<


In reply to Re^2: Removing unwanted chars from filename. by AnomalousMonk
in thread Removing unwanted chars from filename. by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.