3

As per perlop, in list context, a matching operator m// with a regex that has a capture group and a /g modifier will return a list of captures:

my $str = "8a9b0c"; my @res = ($str =~ m/(\d)/g); print @res;

# Prints "8 9 0"

However, I can't find in either perlop or prelre any mention of why substitution operator will instead - even in list context - return the number of captures:

my $str = "8a9b0c"; my @res = ($str =~ s/(\d)//g); print "@res\n"

prints "3"

Why and where is that behavior documented?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
DVK
  • 126,886
  • 32
  • 213
  • 327

2 Answers2

4

From perlop:

Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made.

No distinction is made between list and scalar context. So it's returning the number of sustitutions, and then assigning that to the list. This simply converts the number to a list containing the number.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

From perlop:

  • s/PATTERN/REPLACEMENT/msixpodualgcer

    Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string).

The docs offers up no alternative spec for list context like the m// operator does.

Miller
  • 34,962
  • 4
  • 39
  • 60