Skip to content

Instantly share code, notes, and snippets.

@thesaravanakumar
Last active July 21, 2024 18:01
Show Gist options
  • Save thesaravanakumar/a9732d8cfd75bdbef437128c641b6ebb to your computer and use it in GitHub Desktop.
Save thesaravanakumar/a9732d8cfd75bdbef437128c641b6ebb to your computer and use it in GitHub Desktop.
perl cheatsheet

Perl Language

  • A dynamic interpreted scripting language famous for text-processing abilities.
  • Developed in 1987 by Larry Wall.
  • When someone says perl usually it's version 5 (version 6 is called RAKU).
  • Offen reffered to as glue language (networking, databases, automation, admin scripts, string parsing).
  • Commonly used to write CGI (Common Gateway Interface) scripts that allows webservers to communicate to external programs.
  • Has powerful string parsing abilities.

Design principle of Perl:

Things that are different should look different

#!/usr/bin/perl

# scalar
$hello = "hi mom";
$num = 1;

# array
@nums =(10,20,30);
@nums[1];

# Hash
%friends = ('Larry', 67, 'Ken', 79);
%friends{'Larry'};

# conditional
if(5>10){
   print "hi";
}
print "hi" if 5>10;
$result = (5>10)? "hi" : "bye";

# Functions are defined as sub routines
sub perlwillbefuntheysaid {
   print "This is a function";
   my($n1,$n2) = @_; #any arguments passed to the function can be accessed by @_
   print $n1 + $n2;
}
   
# Regex are built-in and =~ can easily match a string
if($text =~ /cool/)

# Autovivification (bring missing data to life)
@counter = (1..10);
$counter[20]++;
$len = @counterl
print $len;

# e for execute
perl -e 'print "hello\n"' 
# E for enabling features "say" is for adding new line
perl -E 'print "hello"'
# <> - taking input, uc - upper case
perl -E 'while(<>) { say uc $_}'
hello
HELLO

File Structure

#!/usr/bin/env perl

use strict; # pragmas
use warnings;

my $test = "random";
print $test . "Hello world!"; #concatinate

1; # returns true (If not used it will throw a warning if you are using a script inside a script)

Scalars - single unit of data, they can hold one of undefined, number, string or reference

$num = 1;
$string = "hello"
print $string . $num . "\n";
hello\n1

Debugging

use Data::Dumper;
my $a = 1;
my $b = "hello";
print Dumper($a,$b);
VAR1 = '1';
VAR2 = 'hello';

Arrays

my @test = qw/one two three/; # qw means quoted words
VAR1 = 'one' VAR2 = 'two' VAR3 = 'three'
print Dumper($test[-1]); # last item in array
$size = @test # size of the array
$last_index = $#test; #last index in an array
@test = (11 .. 30); # creates 11 to 30 array
print Dumper( @test[2 .. 3]); # prints the index value
push @test, 20 # push at end
pop @test # remove last element
shift @test # removes first element
unshift @test, 20 # adds element in front

#sort
my @test = qw/ h o p m l a b c /;
@test = sort @test; # sorts a string too
my test = (4,2,10,22,30);
@test = sort @test;
10, 2, 22, 30, 4 # not good becaue it sorts based on string context
@test = sort {$a <=> $b} @test;

Hashes

  • Key value pair.
  • Order is not preserved, never!
  • Keys are unique so values are overwrittern if there is same key name.
my %map = (
   a => 20,
   b => "hello",
   c => 11.22,
);
$map{d} = 10;
print Dumper( $map{c} ); # 11.22

# merge two maps
my %map2 = (
   e => 1,
   %map
);

# access slice of hashes using array
print Dumper (@map{'a','b'});
@arrays = keys %map; #returns all the keys
$size = keys %map; # returns the size of the hash
my $exists = exists $map{d} ? "yes" : "no" ; # key exits or not
delete $map{c}; # deletes an item from a hash

References

  • A location in a memory that points to an another data structure.
  • Allows you to construct nested data structures.

pass by value = you are duplicating the value in memory pass by reference = you are passing the location of the data structure in your memory

my %hash = (a=>1,b=>2);
my @array = qw/string1 string2/;
my $scalar = 32;
print \%hash # HASH(0x7fee57825820)

# Dereference
my @array = qw/string1 string2/;
my $ref1 = \@array;
push $ref1, "new"; # won't work
push $ref1->@*,"new"; # ->@ dereference to array so you can push new items by reference of an array

# References
my $hash_ref = {
   hello => 1,
   world => 2,
};
my $array_ref = [ 1,2,3 ];
print Dumper($hash_ref->{a}); dereferences
print Dumper($array_ref->[1]);
print Dumper($hash_ref->%*); dereference a whole hash
print Dumper(@$array_ref);
my $hash_ref = {
   a => 1,
   b => 2,
   c => { # nested!
      new => 1,
      new2 => 2,
      deep = [1,2]
   }
}; 
print Dumper($hash_ref->{c}->{deep}->[0]); # 2
delete $hash_ref->{b};
print Dumper(values $hash_ref->%*); # dereference

Subroutines

  • Same as Function.
  • A group of function encapsulated in a single function to perform a specific task.
  • Perl is going to return the last value you worked with in a function so no need to return.
sub test {
   my $name = $_[0]; # gets the first item
   my @args = @_;
   my $name = $args[0]; # gets the first item
   print "Hello $name!\n";
}
test("John");

# reference 
my @array = qw/a b c/;
sub test{
   my $arg = shift @_;
   push $arg->@*, "hello";
};
test(\@array);
print Dumper(@array);

# signatures
use feature qw/ signatures /; # importing signatures
sub test ($name){ # add required parameters
   print "Hello, $name";
}
test("John");

sub test ($name = undef){} # optional parameter it can be undef or defaults to any name ($name = "Bob")

Scopes

  • my - Local
  • our - Global
script.pl
our $name = "Bob"; #my won't work

script2.pl
require './script.pl'
our ($name);
print "$name";

# state feature - initialize once in a memory
sub test{
   state $var = 1; # my means 2 2 2
   $var +=1;
   print '>>>>' . $var . "\n";
}
test();
test();
test();
# 2 3 4

Error Handling

  • die - perl will not execute after this line.
  • $@ - Holds the value of the exception.
  • warn - does not stops execution after this line.
  • eval - Handles exception.
my $test = "world";
eval {
   die 'cannot go on';
   $test = 'bob';
};
print "hello $test: $@\n";
# hello world cannot go on at script.pl line 5.

Logical Operation

say 20 <=> 40
# 0 if equal, 1 if lhs is larger, -1 if rhs is larger
# for strings 'a' eq 'b' (eq, ne, lt, gt, ge, le) 

# repetition
my $str = "h" x 5;
say $str; # hhhhh

Conditional

if(){}
elseif(){}
else{}
unless(){} #if false run

my $test = 1;
$test = 2 if 2 > 1;
$test = 2 unless 2 > 1;

Loops

  • If you are modifying a variable inside a loop it will affect the variable outside the loop.
while(){}
for(init;cond;inc/dec){}

Loop2:
foreach my $item(@list){
   next if $item == 2; # scips the 2
   last if $item == 2; # ends the loop when 2, won't execute after
   redo if $item == 2; # redos the loop
   goto Loop2 $item == 2; # goes to the tag Loop2
   say "hello, $item";
}

Regular Expressions

Reference: https://www.youtube.com/playlist?list=PLzG1TFYtKG9eyjtlvOMiVBU4YH4xae-GI

@thesaravanakumar
Copy link
Author

It will be easy they said...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment