Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Removing unwanted chars from filename.

by hippo (Bishop)
on Oct 06, 2022 at 18:40 UTC ( #11147277=note: print w/replies, xml ) Need Help??


in reply to Removing unwanted chars from filename.

If you are stripping out all characters from a known set then tr is the way to go for 2 reasons. Firstly, it's lightning fast. Secondly you cannot accidentally construct a pattern of more than a single character. Here is a test to demonstrate.

#!/usr/bin/env perl use strict; use warnings; use Test::More tests => 1; my $in = q/xTest-1 [ ] 'copy'.png /; my $want = 'xTest-1copy.png'; my $have = filter ($in); is $have, $want; sub filter { my $str = shift or return ''; return $str =~ tr/A-Za-z0-9.-//cdr; }

🦛

Replies are listed 'Best First'.
Re^2: Removing unwanted chars from filename.
by AnomalousMonk (Archbishop) on Oct 06, 2022 at 23:13 UTC
    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. :)


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

      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://11147277]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2023-03-26 19:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (63 votes). Check out past polls.

    Notices?