Home Perl
Post
Cancel

Perl

Variables

Scalar Variables

1
2
3
4
5
6
$var = "value";        # Public variable
my $var = "value";     # Private variable
local $var = "value";  # Localized variable

# Constants
use constant PI => 3.14;

Array Variables

1
@arr = (1, 2, 3);      # Array declaration

Hash Variables

1
%hash = (key1 => "value1", key2 => "value2");

Arrays

Array Operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Adding elements
push(@arr, 4);         # Add to end
unshift(@arr, 0);      # Add to beginning

# Removing elements
pop(@arr);             # Remove from end
shift(@arr);           # Remove from beginning
splice(@arr, 1, 1);    # Remove element at index 1

# Accessing elements
$first = $arr[0];      # Get first element
@slice = @arr[0, 1, 2];# Get multiple elements

# Modifying elements
$arr[0] = 10;          # Set single element
@arr[0, 1, 2] = (1, 2, 3); # Set multiple elements

# Array information
$len = scalar @arr;    # Get array length
$last_index = $#arr;   # Get last index

Array Functions

1
2
3
@sorted = sort @arr;           # Sort ascending
@reverse_sorted = reverse sort @arr; # Sort descending
@unique = uniq @arr;           # Remove duplicates (requires List::MoreUtils)

Hashes

Hash Operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Adding/modifying elements
$hash{new_key} = "new_value";

# Accessing elements
$value = $hash{key};

# Removing elements
delete $hash{key};

# Check if key exists
if (exists $hash{key}) { ... }

# Get keys and values
@keys = keys %hash;
@values = values %hash;

Control Structures

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# If-else
if ($condition) {
    # code
} elsif ($another_condition) {
    # code
} else {
    # code
}

# Loops
for my $i (0..10) { ... }          # C-style for loop
foreach my $item (@array) { ... }  # Iterate over array
while ($condition) { ... }         # While loop
do { ... } while ($condition);     # Do-while loop

Subroutines

1
2
3
4
5
6
7
8
sub function_name {
    my ($param1, $param2) = @_;
    # function body
    return $result;
}

# Calling a function
my $result = function_name($arg1, $arg2);

File Operations

1
2
3
4
5
6
7
8
9
10
11
12
# Reading a file
open(my $fh, '<', 'filename.txt') or die "Cannot open file: $!";
while (my $line = <$fh>) {
    chomp $line;
    # Process $line
}
close $fh;

# Writing to a file
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
print $fh "Content to write\n";
close $fh;

Regular Expressions

1
2
if ($string =~ /pattern/) { ... }  # Match
$string =~ s/old/new/g;            # Substitution

Modules

1
2
use Module::Name;                  # Import module
use Module::Name qw(func1 func2);  # Import specific functions
This post is licensed under CC BY 4.0 by the author.