by nineteen999 · 7y ago · 0 comments
If you're in a hurry and just need to do some one-off slicing and dicing, there's not much more powerful than being able to say, eg:
$data = "foobarfoo";
$data =~ s/bar/baz/g;
print "$data\n";
versus python's more dramatic and formal: import re
data = "foobarfoo"
data = re.sub('bar', 'baz', data)
print data
For some reason, the Perl =~ notation sticks in my head
much more easily than the Python method.Of course you can string a bunch of sed commands together in a shell script as well, but I find that becomes unwieldy pretty quickly in a lot of situations.
In other languages a part of me always feels like if I'm using regex I'm doing something wrong, because I used it so liberally in Perl. It feels like a Perl-ism so I try to make a conscious effort not to carry those over as they tend to be the source of inefficiencies.
str.replace = replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
(though the documentation turns out more misleading than re.sub's: this states it replaces all occurrences but really replaces all non-overlapping occurrences, which re.sub actually spells out properly).I found only one very weird edge case worth noting, in Perl the regex "s/ a* / x /g" (spaces added to prevent formatting) will turn the string "bac" into "xbxxcx" because the "a" technically means zero or more so it matches the spaces between the characters, not so in python it creates the string "xbxcx" because it matched the a in between one time and didn't count the empty spaces. Slightly less accurate results since * does mean zero or more so the space between counts as zero characters.
And coming to Perl vs Python regex differences, there are too many to count, Python's 3rd party module 'regex' is more comparable to Perl regex. For example, Python doesn't support possesive quantifiers, subexpression calls, \K, \G and so on
$data = "foobarfoo"
say $data =~ s/bar/baz/gr
say is like print, but adds a newline as well.The /r option does a non destructive replace and returns the result.
The gap between perl and python seems cleaner than the gap between python and anything-statically-typed, at least.