I got a headache looking for this:
How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I’m looking for a perl equivalent of python’s re.sub(…) when used in the following context:
newstring = re.sub('ab', 'cd', oldstring)
The only way I know how to do this in perl so far is:
$oldstring =~ s/ab/cd/;
$newstring = $oldstring;
Note the extra assignment.
You seem to have a misconception about how
=~works.=~is a binding operator that associates a variable with a regexp operator. It does not do any assignment.The regexp operators all work by default with the topic variable
$_, sos/foo/bar/;is the same as$_ =~ s/foo/bar/;. No assignment occurs. The topic variable is transformed.The case is analogous when operating on any other variable.
$var =~ s/foo/bar/;transforms$varby replacing the first instance offoowithbar. No assignment occurs.The best advice I can give you is to write Python in Python and Perl in Perl. Don’t expect the two languages to be the same.
You could do like DVK suggests and write a subroutine that will reproduce the substitution behavior you are used to.
Or you could try some idiomatic Perl. Based on your expressed desire to apply multiple transformations in one line, I’ve provided a couple examples you might find useful.
Here I use a
forloop over one item to topicalize$varand apply many hard-coded transformations:Or maybe you need to apply a variable group of transforms. I define a subroutine to loop over a list of array references that define old/new transformation pairs. This example takes advantage of Perl’s list oriented argument processing to handle any number of transformations.
Finally a bit of messing about to provide a version of transform that modifies its first argument:
For my own project I’d probably use one of the first two options depending on the needs of the particular problem.