Arrays
my @arr = (1,2,3); $arr[49] = 50; # Inserts empty items to 49th element! my @words = qw( quoted words are cleverly done like this); $last_index = @arr; $arr_size = scalar(@arr); ##### Referencing Values ##### print $arr[0]; # First value; print @arr[0..2,1]; # elements 0 through 2, element 1 ##### Stacks and Queues ##### push @stack, $var; # inserts at end $var = pop @stack; # removed from end push @queue, $var; # inserts at end $var = shift @queue; # removes from beginning unshift @dequeue, $var; # insert at beginning $var = pop @dequeue; # remove from end ##### Iterations (Loops) ###### foreach my $elem (@array) { print $elem; } for (my $i=0; $i<=@#array; $i++) { print $array[$i]; } for (my $i=0; $i<scalar(@array); $i++) { print $array[$i]; } while (my $elem = shift @array) { print $elem; } # Note that @array is destroyed ##### Cool Functions ##### @arr = sort @arr; ##### True or False? ##### # True if defined and has at least 1 element in array if (@arr) ...
Now let’s see that as references!
my $arr = [1,2,3]; $arr->[49] = 50; # Inserts empty items to 49th element! my $words = \qw( quoted words are cleverly done like this); $last_index = @$arr; $arr_size = scalar(@$arr); ##### Referencing Value ##### print $arr->[0]; # first item print @$arr; # Whole array print @{$arr}; # Whole array # the last syntax can handle complex values such as... print @{$hash->{key}}; # A hash reference to an array ref. print @{$arr}[0,2]; # Returns element 0 and 2 as a list ##### Stacks and Queues ##### push @$stack, $var; # inserts at end push @{$stack}, $var; # inserts at end $var = pop @$stack; # removed from end push @$queue, $var; # inserts at end $var = shift @$queue; # removes from beginning unshift @$dequeue, $var; # insert at beginning $var = pop @$dequeue; # remove from end ##### Iterations (Loops) ###### foreach my $elem (@$array) { print $elem; } for (my $i=0; $i<=@#$array; $i++) { print $array->[$i]; } for (my $i=0; $i<scalar(@$array); $i++) { print $array->[$i]; } while (my $elem = shift @$array) { print $elem; } # Note that @array is destroyed ##### Cool Functions ##### @arr = sort @$arr; ##### True or False? ##### # True if defined and has at least 1 element in array if (@$arr) ... # True if an array reference... if (ref($arr) eq 'ARRAY') ...