Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You seem to have a misconception about how <code>=~</code> works. <code>=~</code> is a binding operator that associates a variable with a regexp operator. It does not do any assignment.</p> <p>The regexp operators all work by default with the topic variable <code>$_</code>, so <code>s/foo/bar/;</code> is the same as <code>$_ =~ s/foo/bar/;</code>. No assignment occurs. The topic variable is transformed.</p> <p>The case is analogous when operating on any other variable. <code>$var =~ s/foo/bar/;</code> transforms <code>$var</code> by replacing the first instance of <code>foo</code> with <code>bar</code>. No assignment occurs.</p> <p>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.</p> <p>You could do like DVK suggests and write a subroutine that will reproduce the substitution behavior you are used to.</p> <p>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.</p> <p>Here I use a <code>for</code> loop over one item to topicalize <code>$var</code> and apply many hard-coded transformations:</p> <pre><code>for( $var ) { s/foo/bar/; s/fizz/buzz/; s/whop/bop-a-loo-bop/; s/parkay/butter/; s/cow/burger/; } </code></pre> <p>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.</p> <pre><code>my $foo = transform( 'abcd' =&gt; [ 'a', 'b' ], [ 'bb', 'c' ], [ 'cc', 'd' ], [ 'dd', 'DONE' ], ); sub transform { my $var = shift; for (@_ ) { my ($old, $new) = @$_; $var =~ s/$old/$new/; } return $var; } </code></pre> <p>Finally a bit of messing about to provide a version of transform that modifies its first argument:</p> <pre><code>my $foo = 'abcd'; transform_in_place( $foo =&gt; [ 'a', 'b' ], [ 'bb', 'c' ], [ 'cc', 'd' ], [ 'dd', 'DONE' ], ); print "$foo\n"; sub transform_in_place { for my $i (1..$#_ ) { my ($old, $new) = @{$_[$i]}; $_[0] =~ s/$old/$new/; } } </code></pre> <p>For my own project I'd probably use one of the first two options depending on the needs of the particular problem.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload