List and Array
List
- init. one element in list.
$fred[0] = "do";
- maximum element index:
$index = $#fred
- last value of list:
$last = $fred[$#fred]
or$last = $fred[-1]
- out-of-bound subscripts return undef, print nothing
- assigning beyond
$#list
, just stretches the list, filling the middle element withundefined
. e.g.$fred[20] = hello
, then $fred[1…19] is there, but undefined
- list e.g. :
(1,2,3)
or("fred", 4.5)
or(1..10)
- e.g.
@ar = (1,2,3,4) @ar[1..3] == 4
is true, because @ar[1..3] in this context, only return 4 which is 4 == 4 - tips:
qw|i am a idoit|
quote each element with" "
, so you don’t need to manually type all quotes. $"
list separator, e.g.$" = "++", print @ar;
will print something like aa++bb++cc++dd
- assignment of list:
($a, $b) = ("a", 2)
- list built up before assignment, swap made easy:
($a, $b) = ($b, $a)
- list built up before assignment, swap made easy:
@
: all of the.@rock = qw(rock1 rock2)
@
can be nested.@rock_more = ("diamond", @rock, "go");
- remove end of array [has side effect]:
$final = pop @num;
- append to end of array [has side effect]:
push @num, 10..15
- remove from beginning [has side effect]:
$first = shift @num;
reverse
andsort
[create copy]
Perl’s Default Scalar: $_
- designer’s choice, programmers don’t need to think about var name and type.
- omit control var from beginning of loop, perl uses
$_
as default control var. for (1..10) { $_ += 10; }
$_ = "perl ruby python"; print
, will print perl ruby python$_
is by default a global variable. However, as of perl v5.10.0, you can use a lexical version of $_ by declaring it in a file or in a block withmy
Scalar, List Context
- designer’s choice: you can’t identify the meaning of expression until you know the context
- e.g.
@people = qw(me mum); @list = @people
list here is list,#num = @people
the number of people, 2 - e.g.
123 + sth
is scalar context, because+
is for scalar ! - e.g.
print @ar."\n"
: is scalar context, print size of array - e.g. scalar (@ar) is scalar context, print size of array
- in a nutshell, if you see some operators belonging to list, then its list context, otherwise, its scalar context.
loop
for $item (@rock = qw(java ruby python)) { $item .= " lang" }
$item
automatically becomemy
var. any outer$item
is unaffected$item
as pointer, assigning to$item
affects the@rock
for (@rock) { $_ = "hard $_" }
" "
evaluates all symbols in it,' '
just treats as literal string