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

How would I replace all . (periods) with a _ (underscore) in a string?

Replies are listed 'Best First'.
Re: Replace all . with _ in a string
by broquaint (Abbot) on Dec 23, 2003 at 15:34 UTC
    The obvious choice would be to use tr e.g
    $_ = 'foo.bar(baz.quux)'; print "was: $_\n"; tr[.][_]; print "now: $_\n"; __output__ was: foo.bar(baz.quux) now: foo_bar(baz_quux)
    See. the perlop manpage for more info.
    HTH

    _________
    broquaint

      And the regexp solution...

      ~s/\./_/g

      Just 'cause TMTOWTDI. And I am not claiming it's the best or worst solution :)


      Play that funky music white boy..
Re: Replace all . with _ in a string
by davido (Cardinal) on Dec 23, 2003 at 23:34 UTC
    While it probably doesn't matter much in many real world situations, I think it's worth mentioning that the tr/// method of transliterating single characters is much more efficient than the s///g method. s///g is, of course, a good way to do it if you're trying to work on multiple characters or complex situations. But for simple "dumb" single-character replacement, tr/// is the right tool for the job.

    The following takes a string of 10,000 characters, and changes all of the characters to an alternate character, and then changes them back to their original state... and repeats that approach 5,000 times for each operator (tr/// and s///g). The results are dramatic, but in real world applications how many times are you going to be performing 5000 iterations of replacing 10,000 single characters? ;)

    use strict; use warnings; use Benchmark; my $string = '.' x 10000; sub tr_test { $string =~ tr/./_/; $string =~ tr/_/./; } sub s_test { $string =~ s/\./_/g; $string =~ s/_/./g; } my $count = 5000; timethese ( $count, { 'TR' => \&tr_test, 'S' => \&s_test } ); __OUTPUT__ Benchmark: timing 5000 iterations of S, TR... S: 48 wallclock secs (46.95 usr + 0.01 sys = 46.96 CPU) @ 106.48/s (n=5000) TR: 0 wallclock secs ( 0.58 usr + 0.00 sys = 0.58 CPU) @ 8605.85/s (n=5000)

    The speed difference is both understandable and breathtaking. And in some applications it might even matter, while in others, it might not. ;)


    Dave

Re: Replace all . with _ in a string
by DigitalKitty (Parson) on Dec 23, 2003 at 19:22 UTC
    Hi.
    #!/usr/bin/perl -w use strict; my $str = "I like to eat pizza. Every friday, I do."; $str =~ s/\./_/g; print $str; Output: C:\>perl pg61.pl I like to eat pizza_ Every friday, I do_


    I had to 'backslash' the period to prevent it from matching any character in the string. The 'g' on the end of the substitution means 'throughout the whole string as opposed to only the first period'.

    Hope this helps,
    -Katie.