in reply to match digit, followed by hyphen, followed again by digit - then add whitespaces and replace in file

G'day fasoli,

TMTOWTDI

An array variable in a quoted (interpolated quotes) string will, by default, add spaces between the elements when interpolated. See 'perlvar: $"' for details.

$ perl -E 'my @x = (1,2,3); say ">@x<"' >1 2 3<

If you get your captures into an array, i.e. ($1,$2,$3), they too will output with spaces separating the elements.

You can do it like this:

$ perl -E 'my @x = "1.234 5.6789 -1.235" =~ /(-?\d+?\.?\d+)/g; say "@x +"' 1.234 5.6789 -1.235 $ perl -E 'my @x = "1.234 5.6789-12.235" =~ /(-?\d+?\.?\d+)/g; say "@x +"' 1.234 5.6789 -12 235

Perl v5.26 introduced some new special variables to handle this sort of thing for you (see "perldelta: @{^CAPTURE}, %{^CAPTURE}, and %{^CAPTURE_ALL}"). Using @{^CAPTURE} removes the need for an intermediate variable. Here's a couple of quick examples with your posted data:

$ perl -E '"1.234 5.6789 -1.235" =~ /^(-?\d+?\.?\d+)\s*(-?\d+?\.?\d+)\ +s*(-?\d+?\.?\d+)$/; say "@{^CAPTURE}"' 1.234 5.6789 -1.235 $ perl -E '"1.234 5.6789-12.235" =~ /^(-?\d+?\.?\d+)\s*(-?\d+?\.?\d+)\ +s*(-?\d+?\.?\d+)$/; say "@{^CAPTURE}"' 1.234 5.6789 -12.235

— Ken

  • Comment on Re: match digit, followed by hyphen, followed again by digit - then add whitespaces and replace in file
  • Select or Download Code