How much is $ 1 to $ 9 perl?

What is the scope $1through $9in Perl? For example, in this code:

sub bla {
    my $x = shift;
    $x =~ s/(\d*)/$1 $1/;
    return $x;    
}

my $y;

# some code that manipulates $y

$y =~ /(\w*)\s+(\w*)/;

my $z = &bla($2);
my $w = $1;

print "$1 $2\n";

What will $1be? Will it be the first \w*of $xor the first \d*of the second \w*in $x?

+5
source share
3 answers

of perldoc perlre

The numbered comparable variables ($ 1, $ 2, $ 3, etc.) and the associated punctuation set ($ +, $ &, $ `, $ 'and $ ^ N) are dynamically covered until the end or until the next successful match, depending from what comes sooner. (See "Connections" in perlsyn.)

, local . (& agrave; la local), . , $1 10 , , 20 10 , .

regex . ,

#!/usr/bin/perl

use strict;
use warnings;

sub bla {
    my $x = shift;
    $x =~ s/(\d*)/$1 $1/;
    return $x;    
}

my $y = "10 20";

my ($first, $second) = $y =~ /(\w*)\s+(\w*)/;

my $z = &bla($second);
my $w = $first;

print "$first $second\n";

$first $second , .

+17

:

sub bla {
    my $x = shift;
    print "$1\n";
    $x =~ s/(\d+)/$1 $1/;
    return $x;
}
my $y = "hello world9";

# some code that manipulates $y

$y =~ /(\w*)\s+(\w*)/;

my $z = &bla($2);
my $w = $1;

print "$1 $2\n$z\n";

:

hello
hello world9
world9 9

, $1 (.. $1, bla, ( $1, $y, bla, ))

+4

Variables will be valid until the next time they are written in the execution thread.

But actually you should use something like:

my ($match1, match2) = $var =~ /(\d+)\D(\d+)/;

Then use $ match1 and $ match2 instead of $ 1 and $ 2, which is much less ambiguous.

+2
source

All Articles