Perl-Sensitive Sunglasses | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Better is $string =~ tr/ /-/; Don't use substitution when transliteration is applicable. Why? I often hear this advice and it usually stems from the fiction that "tr/// is always faster than s///". A better rule, IMHO, is to use the tool that fits best. In this case, both fit equally well. I personally prefer s/ /-/g because it will be recognized more widely. If I felt that the requirement was likely to become something like "change ' ' to '-' and tab to '_'", then I might start with tr/ /-/ in expectation of changing it to something like tr/ \t/-_/ (which could be done with s/// but not so cleanly). While if I felt that the requirement was likely to become something like "change whitespace to '-'", then I'd start with s/ /-/g in expectation of changing it to something like s/\s+/-/g (which could be done with tr/// but not so cleanly). In the very rare case where the performance difference between the two matters, which to use depends on your input. Benchmarking with one 10kB string I get: [ Note that "0s" and "1s" are identical as are "0tr" and "1tr". I usually include such so that runs of each case are interleaved so I get an idea how much variability there is between runs vs. real differences in performance. ] With a different 10kB string I get: Note that in both cases, the speed difference between s/// vs. tr/// is only a few micro seconds on a 10kB string so this is extremely unlikely to matter either way for the vast majority of uses. - tye In reply to Re^3: String Manupulation (yarn)
by tye
|
|