perl - Backslash before a subroutine call -
as understanding difference between [] , \ in references,i used both on subroutine former fine when tried later thought should give error below program in perl
#!/usr/bin/perl use strict; use warnings; use data::dumper; @b; $i ( 0 .. 10 ) { $b[$i] = \somefunc($i); } print dumper( \@b ); sub somefunc { $n = shift; ( @a, $k ); $j ( 11 .. 13 ) { $k = $n * $j; push( @a, $k ); } print "a: @a \n"; return @a; }
gives output :
a: 0 0 0 a: 11 12 13 a: 22 24 26 a: 33 36 39 a: 44 48 52 a: 55 60 65 a: 66 72 78 a: 77 84 91 a: 88 96 104 a: 99 108 117 a: 110 120 130 $var1 = [ \0, \13, \26, \39, \52, \65, \78, \91, \104, \117, \130 ];
i unable understand output.need explanation.
what happening here is:
you returning array somefunc
.
but assigning scalar. effectively doing therefore, putting last value in array, scalar value.
my $value = ( 110, 120, 130 ); print $value;
when - $value set last value in array. what's happening in code. see example perldata
:
list values denoted separating individual values commas (and enclosing list in parentheses precedence requires it):
(list)
in context not requiring list value, value of appears list literal value of final element, c comma operator. example,
@foo = ('cc', '-e', $bar);
assigns entire list value array
@foo
, but
foo = ('cc', '-e', $bar);
assigns value of variable $bar scalar variable $foo. note value of actual array in scalar context length of array; following assigns value 3 $foo:
@foo = ('cc', '-e', $bar);
$foo = @foo; # $foo gets 3
it's latter case that's gotcha, because it's list in scalar context.
and in example - backslash prefix denotes 'reference to' - largely meaningless because it's reference number.
but scalar, might more meaningful:
my $newvalue = "fish"; $value = ( 110, 120, 130, \$newvalue ); print dumper $value; $newvalue = 'barg'; print dumper $value;
gives:
$var1 = \'fish'; $var1 = \'barg';
that's why you're getting results. prefix slash indicates you're getting reference result, not reference sub. reference 130
isn't meaningful.
normally, when doing assignment above - you'd warning useless use of constant (110) in void context
doesn't apply when you've got subroutine return.
if wanted insert sub reference, you'd need add &
, if want insert returned array reference - either need to:
$b[$i] = [somefunc($i)]
or:
return \@a;
Comments
Post a Comment