experchange > perl

Henry Law (01-17-20, 04:07 PM)
I need to detect a string of the form "textN+" or "text Nx" (where N is
a single digit) and put a period in before the N, thus
"foo8+" -> "foo.8+".
"foo8x" -> "foo.8x".

Sample code:

#!/usr/bin/perl
use strict;use warnings;use 5.014;

my $event_string = "S38+";
if ( $event_string =~ /[^\.](\d[x+])$/ ){
my $boat = $1;
print "Inserting period before '$boat' in '$event_string'\n";
$event_string =~ s/$boat/\.$boat/;
print " --> $event_string\n";
}

Result: ~/Perl/tryout/tryout
Inserting period before '8+' in 'S38+'
--> S3.8++

Where does my second plus sign come from? I've looked at this all ways
up and I can't find out what I'm doing wrong.
Jörg Westheide (01-17-20, 04:31 PM)
Hi Henry!

> Result: ~/Perl/tryout/tryout
> Inserting period before '8+' in 'S38+'
> --> S3.8++
> Where does my second plus sign come from? I've looked at this all
> ways up and I can't find out what I'm doing wrong.


The problem is with your substitution:

> $event_string =~ s/$boat/\.$boat/;


The first occurrence of $boat in the substitution is interpreted as a
regex pattern. So it actually is s/8+/.8+/ which replaces a sequence of
'8' characters with the string ".8+". To prevent this disable the
interpretation of pattern metacharacters in $boat:

$event_string =~ s/\Q$boat\E/\.$boat/;

Jörg
Henry Law (01-17-20, 05:02 PM)
On 17/01/2020 14:31, Jörg Westheide wrote:
> The first occurrence of $boat in the substitution is interpreted as a
> regex pattern.


Blindingly simple when you explain it like that ... but I was a long way
from looking carefully enough to find it. Thank you very much.
Rainer Weikusat (01-17-20, 05:09 PM)
Henry Law <news> writes:
[..]
> Result: ~/Perl/tryout/tryout
> Inserting period before '8+' in 'S38+'
> --> S3.8++


Is there a reason why you aren't just doing this with a s///?

-----
#!/usr/bin/perl
use strict;use warnings;use 5.014;

my $event_string = "S38+";

$event_string =~ s/(?<!\.)(\d[x+])$/.$1/;
print " --> $event_string\n";
Henry Law (01-17-20, 06:56 PM)
On 17/01/2020 15:09, Rainer Weikusat wrote:
> Is there a reason why you aren't just doing this with a s///?


TMTOWTDI and I didn't think of it.

But thank you for the suggestion.
Rainer Weikusat (01-18-20, 12:42 AM)
Henry Law <news> writes:
> On 17/01/2020 15:09, Rainer Weikusat wrote:
>> Is there a reason why you aren't just doing this with a s///?

> TMTOWTDI and I didn't think of it.
> But thank you for the suggestion.


The substitution is probably faster (which probably doesn't matter) and
it avoids the need to tell Perl that it shouldn't interpret the
extracted string as regex.
Similar Threads