Reading — step 1 of 5
Learn
~1 min readLists, Arrays, and Hashes
Arrays are ordered, zero-indexed:
my @nums = (3, 1, 4, 1, 5, 9, 2, 6);
print $nums[0], "\n"; # 3 — note the $ sigil!
print scalar @nums, "\n"; # 8 (length)
push @nums, 5; # append
unshift @nums, 0; # prepend
my $last = pop @nums; # remove and return last
my $first = shift @nums; # remove and return first
my @sorted = sort { $a <=> $b } @nums; # numeric sort
my @reversed = reverse @nums;
Sigil-changing magic: @nums is the whole array, but $nums[0] is one element (it's a scalar, so use $). This trips everyone up at first.
@_ is the implicit argument array inside a function:
sub greet {
my ($name) = @_;
print "Hello, $name!\n";
}
Slices:
my @nums = (10, 20, 30, 40, 50);
my @two = @nums[1, 3]; # (20, 40) — note @ sigil for multiple
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…