http://www.perlmonks.org?node_id=11147277


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