Perl
Scalars, Arrays, and Hashes
Perl's three main data types with sigils.
By EZ4Code Team
scalararrayhash
Code
use strict;
use warnings;
# Scalar ($)
my $name = "Alice";
my $age = 30;
my $pi = 3.14159;
# Array (@)
my @colors = ("red", "green", "blue");
print $colors[0]; # "red" (scalar access uses $)
print scalar(@colors); # 3 (length)
push @colors, "yellow"; # append
unshift @colors, "black"; # prepend
my $last = pop @colors; # remove last
my $first = shift @colors; # remove first
my @slice = @colors[0, 1]; # array slice
# Hash (%)
my %person = (
name => "Alice",
age => 30,
city => "NYC",
);
print $person{name}; # "Alice" (scalar access uses $)
@person{qw(name age)} = ("Bob", 25); # hash slice
my @keys = keys %person;
my @values = values %person;
while (my ($k, $v) = each %person) {
print "$k => $v\n";
}Explanation
Perl uses sigils to indicate type: $ for scalar (single value), @ for array (ordered), % for hash (key-value). The sigil changes when accessing a single element: $array[0], $hash{key}. qw() creates word lists without quotes. => is a fat comma (auto-quotes the left side). Always use strict and warnings to catch bugs.
More Perl Snippets
Regular Expressions
Perl is famous for its powerful regex support.
Subroutines and References
Define subs and use references for complex data.
Complex Data Structures
Build nested structures with references.
Modules and Packages
Create reusable modules with package keyword.
File I/O
Read and write files with filehandles.
OOP with Moose
Modern object-oriented programming in Perl.