Passing a scalar link in Perl

I know that passing a scalar to sub actually passes the link, but since I'm new to perl, I still ran the following test:

#!/usr/bin/perl
$i = 2;
subr(\$i);
sub subr{
    print $_[0]."\n";
    print $$_[0]."\n";
}

I thought the first line would print the address, and the second line would return the number, and the second would be the empty string. I was pointed out by someone else to do this: ${$_[0]}and it prints the number. But she did not know the reason why without {} she does not work and why she works with {}. So what happened?

+5
source share
4 answers

This is because your second print statement is equivalent to this ...

my $x = $$_; print $x[0];

When do you want,

my $x = $_[0]; print $$x;

In other words, de-binding occurs before evaluating the index of the array.

curl-wurlies, perl, , ; $_[0], -, .

+13

.

  $$_[0] is evaluated as {$$_}[0]

0- $_. , 0- .

  ${$_[0]}

0- @_. 0- , .

use strict use warnings , undefined .

+7

$$_[0] $foo[0], $_ . , $_ , $_[0]. $_->[0] , ->. , ; - http://perlmonks.org/?node=References+quick+reference.

+3

$i. $_[0] $i, subr( $i ).

use strict;
use warnings;
use Test::More tests => 2;

sub subr{ $_[0]++ } # messing with exactly what was passed first
my $i=2;
is( $i, 2, q[$i == 2] );
subr($i);
is( $i, 3, q[$i == 3] );

:

use strict;
use warnings;
use Test::More tests => 6;
use Test::Exception;

sub subr{ $_[0]++ }
my $i=2;
is( $i, 2, q[$i == 2] );
subr($i);
is( $i, 3, q[$i == 3] );

sub subr2 { $_[0] .= 'x'; }
dies_ok { subr2( 'lit' ); } 'subr2 *dies* trying to modify a literal';
lives_ok { 
    my $s = 'lit';
    subr2( $s );
    is( $s, 'litx', q[$s eq 'litx'] );
    subr2(( my $s2 = 'lit' ));
    is( $s2, 'litx', q[$s2 eq 'litx'] );
} 'subr2 lives with heap variables';

:

ok 1 - $i == 2
ok 2 - $i == 3
ok 3 - subr2 *dies* trying to modify a literal
ok 4 - $s eq 'litx'
ok 5 - $s2 eq 'litx'
ok 6 - subr2 lives with heap variables
1..6
+1

All Articles