Variable values

I was wondering if there is a simple / clean way to replace values ​​as follows, possibly using a single regular expression / replacement?

If $ a ends with "x", replace it with "y". And similarly, if $ a ends with "y", replace it with "x":

$a = "test_x"; if ($a =~ /x$/) { $a =~ s/x$/y/; } else { $a =~ s/y$/x/; } 

I can only think of something like this:

 $a = $a =~ /x$/ ? s/x$/y/ : s/y$/x/; 
+5
source share
3 answers

It's simple:

 $a =~ s/x$/y/ or $a =~ s/y$/x/; 

It is almost always redundant to make a match to see if you should make a replacement.

Another way:

 substr($a,-1) =~ y/xy/yx/; 
+10
source

You can compress it in a string as you show, perhaps a little better with /r (with v5.14 +).

Or you can prepare a hash. It also frees the code from hard coding certain characters.

 my %swap = (x => 'y', y => 'x', a => 'b', b => 'a'); # expand as needed my @test = map { 'test_' . $_ } qw(xyab Z); for my $string (@test) { $string =~ s| (.)$ | $swap{$1} // $1 |ex; say $string; } 

// (defined-or) should handle the case when the last character is not in the hash, in which case $swap{$1} returns undef . Thanks to user52889 for the comment.

+5
source

To change individual characters, you can use tr/// .

Not sure what your criteria for cleanliness or ease are, but you can even do this on the right side of the replacement:

 $xy = "test_x" =~ s`([xy])$`$1=~tr/xy/yx/r`re; # $xy is "test_y" 
+3
source

Source: https://habr.com/ru/post/1261748/


All Articles