700 Software
700 Software

Reputation: 87833

Is this line of Perl meaningless? s/^(\d+)\b/$1/sg

Does this line of Perl really do anything?

$variable =~ s/^(\d+)\b/$1/sg;

The only thing I can think of is that $1 or $& might be re-used, but it is immediately followed by.

$variable =~ s/\D//sg;

With these two lines together, is the first line meaningless and removable? It seems like it would be, but I have seen it multiple times in this old program, and wanted to make sure.

Upvotes: 8

Views: 2675

Answers (2)

Mikel
Mikel

Reputation: 25626

Is "taint mode" in use? (Script is invoked with -T option.)

Maybe it's used to sanitize (i.e. untaint) user input.

Upvotes: 6

TLP
TLP

Reputation: 67910

$variable =~ s/^(\d+)\b/$1/sg;
  • The anchor ^ at the beginning makes the /g modifier useless.
  • The lack of the wildcard character . in the string makes the /s modifier useless, since it serves to make . also match newline.
  • Since \b and ^ are zero-width assertions, and the only things outside the capture group, this substitution will not change the variable at all.

The only thing this regex does is capture the digits into $1, if they are found.

The subsequent regex

$variable =~ s/\D//sg;

Will remove all non-digits, making the variable just one long number. If one wanted to separate the first part (matched by the first regex), the only way to do so would be by accessing $1 from the first regex.

However, the first regex in that case would be better written simply:

$variable =~ /^(\d+)\b/;

And if the capture is supposed to be used:

my ($num) = $variable =~ /^(\d+)\b/;

Upvotes: 12

Related Questions