简体   繁体   中英

Perl regular expressions troubles

I have a variable $rowref->[5] which contains the string:

"  1.72.1.13.3.5  (ISU)"

I am using XML::Twig 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 XML::Twig 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?

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/([^0-9\.])//g;
$artifact->set_att(version => $version);

The regex substitution changes the varialbe in place but returns the number of substitutions it made ( 1 without the /g modifier, if it was succesful).

my $str = 'words 123';
my $ret = $str =~ s/\d/numbers/g;
say "Got $ret. String is now: $str";

You can do the substitution first, $rowref->[5] =~ s/...//; , and then use the changed variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM