3.6 KiB
3.6 KiB
Perl Cheat Sheet
Basics
Comments
# This is a comment
print "Hello, World!\n";
Variables
$scalar_variable = 42;
@array_variable = (1, 2, 3);
%hash_variable = ('key' => 'value');
Control Structures
if-else
if ($condition) {
# Code to execute if condition is true
} else {
# Code to execute if condition is false
}
foreach
foreach $item (@array) {
# Code to execute for each item in the array
}
while
while ($condition) {
# Code to execute while condition is true
}
Subroutines
sub greet {
my $name = shift;
print "Hello, $name!\n";
}
greet("Alice");
Regular Expressions
Matching
if ($string =~ /pattern/) {
# Code to execute if pattern is found in $string
}
Substitution
$string =~ s/find/replace/;
File Handling
Open and Read
open(my $file, '<', 'filename.txt') or die "Can't open file: $!";
while (<$file>) {
chomp;
print "$_\n";
}
close($file);
Open and Write
open(my $file, '>', 'output.txt') or die "Can't open file: $!";
print $file "Hello, File!\n";
close($file);
Modules
Using Modules
use Module::Name;
Exporting Functions
use Module::Name qw(function1 function2);
References
Scalar Reference
$scalar_ref = \$scalar_variable;
Array Reference
$array_ref = \@array_variable;
Hash Reference
$hash_ref = \%hash_variable;
Advanced Perl Cheat Sheet
Basics
Comments
# This is a comment
print "Hello, World!\n";
Variables
$scalar_variable = 42;
@array_variable = (1, 2, 3);
%hash_variable = ('key' => 'value');
Data Types
$string = "Perl";
$number = 42;
$float = 3.14;
Control Structures
if-else
if ($condition) {
# Code to execute if condition is true
} elsif ($another_condition) {
# Code to execute if another condition is true
} else {
# Code to execute if all conditions are false
}
foreach
foreach $item (@array) {
# Code to execute for each item in the array
}
while
while ($condition) {
# Code to execute while condition is true
}
Subroutines
sub greet {
my $name = shift;
print "Hello, $name!\n";
}
greet("Alice");
Returning Values
sub add {
my ($num1, $num2) = @_;
return $num1 + $num2;
}
my $result = add(3, 4);
print "Sum: $result\n";
Regular Expressions
Matching
if ($string =~ /pattern/) {
# Code to execute if pattern is found in $string
}
Substitution
$string =~ s/find/replace/;
File Handling
Open and Read
open(my $file, '<', 'filename.txt') or die "Can't open file: $!";
while (<$file>) {
chomp;
print "$_\n";
}
close($file);
Open and Write
open(my $file, '>', 'output.txt') or die "Can't open file: $!";
print $file "Hello, File!\n";
close($file);
Modules
Using Modules
use Module::Name;
Exporting Functions
use Module::Name qw(function1 function2);
References
Scalar Reference
$scalar_ref = \$scalar_variable;
Array Reference
$array_ref = \@array_variable;
Hash Reference
$hash_ref = \%hash_variable;
Structuring a Perl Script for Bash
Create a Perl Script
#!/usr/bin/perl
use strict;
use warnings;
# Perl script code here
print "Hello from Perl!\n";
Make it Executable
chmod +x script.pl
Run from Bash
./script.pl