scarne7 has asked for the wisdom of the Perl Monks concerning the following question:

Need to write a perl script that will replace space with an "_". This needs to be done to files in a directory,

Replies are listed 'Best First'.
Re: problem with removing space
by azatoth (Curate) on Apr 03, 2001 at 21:12 UTC

      For better performances you'd probably prefer to use a translation instead of a substitution.

      perl -MBenchmark -e 'timethese(1000000,{ "s" => "$_=qq(a a a a a a ); s/ /_/g", "tr" => "$_=qq(a a a a a a ); tr/ /_/", })' Benchmark: timing 1000000 iterations of s, tr... s: 15 wallclock secs (13.81 usr + 0.00 sys = 13.81 CPU) @ 72411.30/s (n=1000000) tr: 5 wallclock secs ( 4.38 usr + 0.00 sys = 4.38 CPU) @ 228519.20/s (n=1000000)
      <kbd>--
      my $OeufMayo = new PerlMonger::Paris({http => 'paris.mongueurs.net'});</kbd>
Re: problem with removing space
by suaveant (Parson) on Apr 03, 2001 at 21:31 UTC
    do this...
    $dir = $ARGV[0]; # get dir from arg list opendir(D, $dir) or die $!; for(readdir(D)) { $file = $_; tr/ /_/; # or tr/ \t\r\n/_/; for tabs and spaces # or s/\s+/_/g; to make multiple whitespace chars into one _ rename("$dir/$file", "$dir/$_"); } closedir(D);
    should work nicely...
                    - Ant

      Note that you can also use tr to squash multiple whitespace characters into single _s:

      $_= " This is \t a test\cM\n"; tr/ \t\f\r\n/_/s; print; __END__ prints "_This_is_a_test_"

              - tye (but my friends call me "Tye")
        Ahhh... I never got into using tr... just one of those things... I should. So how do you make tr trade one for one?
        tr/ \t\f\r\n/_____/
                        - Ant