UsefulUserName UsefulUserName - 1 year ago 101
Perl Question

Perl regular expressions troubles

I have a variable

which contains the string:

" (ISU)"

I am using
to build modify an XML file and this variable contains the information for the version number of something. So I want to get rid of the whitespaces and the (ISU). I tried to use a substitution and
to set the attribute:

$artifact->set_att(version=> $rowref->[5] =~ s/([^0-9\.])//g)

Interestingly what I got in my output was

<artifact [...] version="9"/>

I don't understand what I am doing wrong. I checked with a regular expression tester and it seems fine. Can somebody spot my error?

Answer Source

The return value of s/// is the number of substitutions it made, which in your case is 9. If you are using at least perl 5.14, add the r flag to the substitution:

If the "/r" (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when "/r" is used. The copy will always be a plain string, even if the input is an object or a tied variable.

Otherwise, go through a temporary variable like this:

my $version = $rowref->[5];
$version =~ s/([^1-9\.])//g;
$artifact->set_att(version => $version);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download