How does the assignment operator (=) in Perl work internally? -


suppose num array,

@num = (1 .. 10); 

to find length use following expression,

$num = @num; 

then used same $num in assignment below.

@slicenum = $num[1 .. 6]; 

i aware slicing array use @num instead of $num. ran without throwing errors. when print value of @slicenum, gave me 2 result.

@slicenum = $num[1 .. 6, 10 .. 20]; 

for above assignment, got 1 result.

although value of $num remains 10, please explain happening in above 2 assignments.

you have discovered bit of perl magic @ work. range operator (aka the flip-flop operator amon points out) .. in scalar context seems want compare range $., when used integers:

$ perl -lwe '@a = 1..10; @foo = $a[1..6]; print @foo'  use of uninitialized value $. in range (or flip) @ -e line 1. argument "" isn't numeric in array element @ -e line 1. 1  $ perl -lwe '$x=<>; @a = 1..10; @foo = $a[1..6]; print @foo' somefile.txt name "main::x" used once: possible typo @ -e line 1. 2 

as darch mentions, $a[1 .. 6] imposes scalar context expression inside subscript: [ expr ]. opposed when using @a[1 .. 6], list context imposed instead.

so, part:

1 .. 6 

in scalar context means if ($. >= 1 , $. <= 6)

when $. uninitialized, returns undef (which evaluates 0 in numeric context) , emits uninitialized warning. when $. not uninitialized (i.e. when file has been opened , read somewhere in program) returns either true or false, or in case 1 or empty string. in case, seems return 1, results in

$num[1 .. 6] 

..evaluating to

$num[1] 

which in return returns element number 1, 2.

so, in short: statement 1 .. 6 has different meaning depending on context. in list context, returns 1,2,3,4,5,6, is, range of integers. in scalar context, returns true (1) if $. (line count) variable between 1 or 6, otherwise returns false (empty string).

here mention of phenomena in documentation:

in list context, returns list of values counting (up ones) left value right value.

[ ... ]

in scalar context, ".." returns boolean value. operator bistable, flip-flop, , emulates line-range (comma) operator of sed, awk, , various editors.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -