Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Removing unwanted chars from filename.

by hippo (Archbishop)
on Oct 06, 2022 at 18:40 UTC ( [id://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?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-07-19 10:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.