Quotation - Capture - Question

Can someone explain why I can use $1twice and get different results?

perl -wle '"ok" =~ /(.*)/; sub { "huh?" =~ /(.*)/; print for @_ }->( "$1", $1 )'

(Found in: How to exclude submatrices in Perl? )

+5
source share
3 answers

Array argument @_does not behave as you think. The values ​​in @_the subroutine are actually aliases for real arguments :

The @_ array is a local array, but its elements are aliases for real scalar parameters.

When you say this:

sub s {
    "huh?" =~ /(.*)/;
    print for @_;
}

"ok" =~ /(.*)/;   
s("$1", $1);

$1 s , , , @_ $1 ( $1, ). s $1 . @_ "ok", $1, print .

:

sub s {
    my @a = @_;
    "huh?" =~ /(.*)/;
    print for @a;
}

:

sub s {
    local $1;
    "huh?" =~ /(.*)/;
    print for @_;
}

"ok", . (, -) , s . my @a = @_; @_, $1; local $1; $1 sub, @_, $1 :

, eval.

- @_ ( , ).

, , Perl, , .

+7

:

  • @_ - . , $_[0], ( ).
  • $1 - ( ), () .

- ("ok"). - $1. , .

+2

This is because perl passes parameters by reference.

What you do is like:

my $a = 'ok';

sub foo {
  $a = 'huh?';
  print for @_;
}

my $b = $a;
foo($b, $a)

When sub foo is called, $ _ [1] is actually an alias for $ a, so its value changes when $ a changes.

+1
source

All Articles