Index |
Core programmers will always use Perl scripts to automate their manual work. Problem is recalling some of common functions, coding tricks. This tutorial notes down these regularly used lines of Perl code. | ||||||||||||||||||||||||||||
1) Books |
Best book to start is the one written by none other than by Perl's authors,
Programming Perl by Larry Wall et al | ||||||||||||||||||||||||||||
2) Enforce variable declaration etc. |
use strict; | ||||||||||||||||||||||||||||
3) Variable declaration |
my $variable = 0; | ||||||||||||||||||||||||||||
4) Declare or define a HASH array |
my %hash_array = ( "KEY" => "VALUE", 'Key' => 'Value' ); | ||||||||||||||||||||||||||||
5) Declare or define a plain array |
my @array = ( 'ELEMENT', 'Element' ); | ||||||||||||||||||||||||||||
6) Getting arguments to script |
my $argument1 = $ARGV[0]; die "Argument 1 not passed\n" unless( $argument1 ); | ||||||||||||||||||||||||||||
7) Environment variables |
my $env1 = $ENV{'ENV1'}; | ||||||||||||||||||||||||||||
8) File operations - open, close |
open( FILE, $input_file ) or die "Can not open $input_file: $!\n"; while( <FILE> ) { chomp; } close( FILE ); | ||||||||||||||||||||||||||||
9) Pattern matching |
if( $variable =~ m/pattern/) { print "Pattern matched\n"; } | ||||||||||||||||||||||||||||
10) Replacing pattern Globally and Ignoring case |
my $pattern_replace_ctr = ($variable =~ s/pattern/replacewith/gi); | ||||||||||||||||||||||||||||
11) Access array element |
print $plain_array[0]; | ||||||||||||||||||||||||||||
12) Access hash array element |
print $hash_array{ 'KEY' }; | ||||||||||||||||||||||||||||
13) In loop |
foreach my $element (@plain_array) { $element = 'new element'; } foreach my $key (keys %hash_array) { $hash_array{ $key } = 'new value'; } | ||||||||||||||||||||||||||||
14) Sorting alphabetically |
my @sorted_array = sort @plain_array; | ||||||||||||||||||||||||||||
15) Sorting numerically |
my @sorted_keys = sort { $a <=> $b } keys %hash_array; | ||||||||||||||||||||||||||||
16) Get (and remove) 1st element of an array |
shift( @array ); | ||||||||||||||||||||||||||||
17) Get (and remove) last element of an array |
pop( @array ); | ||||||||||||||||||||||||||||
18) Add an element at the beginning of an array UNSHIFT/SHIFT work like queue (FIFO)operations |
unshift( @array, $element ); | ||||||||||||||||||||||||||||
19) Add an element at the end of an array. PUSH/POP works like stack (LIFO) operations |
push( @array, $element ); | ||||||||||||||||||||||||||||
20) Pointers |
$ptr2var = $var; $$ptr2var = 'new var value' ; $ptr2array = @array; $$ptr2array[0] = 'new 0th element of array'; #Or $ptr2array->[0] = 'new 0th element of array'; $ptr2hash = %hash_array; $$ptr2hash{ KEY } = 'new value for KEY'; #Or $ptr2hash->{ KEY } = 'new value for KEY'; | ||||||||||||||||||||||||||||
21) Array size |
my $array_size = $#array; #Or my $array_size = SCALAR( @array ); | ||||||||||||||||||||||||||||
22) Delete a key from hash array |
delete $hash_array{ 'KEY' }; | ||||||||||||||||||||||||||||
23) All values of hash |
@values = values %hash_array; | ||||||||||||||||||||||||||||
24) Check if file exists |
if ( -e $filename ) { print "File $filename exists.\n"; } | ||||||||||||||||||||||||||||
25) Get filesize |
my $filesize = -s $filename; | ||||||||||||||||||||||||||||
26) Check whether directory |
if( -d $filename ) { print "$filename is directory.\n"; } | ||||||||||||||||||||||||||||
27) Reading directory recursively |
my @files = ($root_dir); while( @files ) { my $file = pop( @files ); if( -d $file ) { opendir( DIR, $file ) or next; my $t_file; while( $t_file = readdir( DIR ) ) { next if( $t_file =~ /^\.$/ ); next if( $t_file =~ /^\.\.$/ ); push( @files, "$file/$t_file" ); } closedir( DIR ); next; } print "File $file ok.\n"; } | ||||||||||||||||||||||||||||
28) Rename the file |
rename( $filename, $new_filename ); | ||||||||||||||||||||||||||||
29) Deleting file |
unlink( $filename ); | ||||||||||||||||||||||||||||
30) Copying file |
use File::Copy; copy( $filename, $copy_of_filename ); | ||||||||||||||||||||||||||||
31) Write into file |
open( OUT_FILE, "> $filename" ) or die "Can not open out file $filename: $!\n"; print OUT_FILE "Test line 1\n"; close( OUT_FILE ); | ||||||||||||||||||||||||||||
32) Append file |
open( OUT_FILE, ">> $filename" ) or die "Can not open out file $filename: $!\n"; print OUT_FILE "Test line 2\n"; close( OUT_FILE ); | ||||||||||||||||||||||||||||
33) Executing system command |
system( $command ); | ||||||||||||||||||||||||||||
34) Functions |
sub test_function { my ($param1, $param2) = @_; my ($out1, $out2); return ($out1, $out2); } | ||||||||||||||||||||||||||||
35) Array of array |
my @array_of_array = ( [ "1 of 1", "2 of 1"], [ "1 of 2", "2 of 2"] ); $array_of_array[0][0] = "New 1 of 1"; $array_of_array[0][1] = "New 2 of 1"; print join( "\n", @{ $array_of_array[0] } )."\n"; | ||||||||||||||||||||||||||||
36) Hash of array |
my %hash_of_array = ( 'KEY1' => [ '1 of KEY1', '2 of KEY1' ], 'KEY2' => [ '1 of KEY2', '2 of KEY2' ] ); $hash_of_array{ 'KEY1' }[0] = 'New 1 of KEY1'; $hash_of_array{ 'KEY1' }[1] = 'New 2 of KEY1'; print join( "\n", @{ $hash_of_array{ 'KEY1' } } )."\n"; | ||||||||||||||||||||||||||||
37) Array of hash |
my @array_of_hash = ( { 'KEY1 of 1st Array' => 'Value of KEY1 of 1st Array', 'KEY2 of 1st Array' => 'Value of KEY2 of 1st Array' }, { 'KEY1 of 2nd Array' => 'Value of KEY1 of 2nd Array', 'KEY2 of 2nd Array' => 'Value of KEY2 of 2nd Array' } ); $array_of_hash[0]{'KEY1 of 1st Array'} = 'New value of KEY1 of 1st Array'; $array_of_hash[0]{'KEY2 of 1st Array'} = 'New value of KEY2 of 1st Array'; print join( "\n", sort keys %{ $array_of_hash[0] } )."\n"; print join( "\n", sort values %{ $array_of_hash[0] } )."\n"; | ||||||||||||||||||||||||||||
38) Hash of hash |
my %hash_of_hash = ( 'HASH1' => { 'KEY1 of HASH1' => 'Value of KEY1 of HASH1', 'KEY2 of HASH1' => 'Value of KEY2 of HASH1', }, 'HASH2' => { 'KEY1 of HASH2' => 'Value of KEY1 of HASH2', 'KEY2 of HASH2' => 'Value of KEY2 of HASH2', } ); $hash_of_hash{ 'HASH1' }{ 'KEY1 of HASH1' } = 'New value of KEY1 of HASH1'; $hash_of_hash{ 'HASH1' }{ 'KEY2 of HASH1' } = 'New value of KEY2 of HASH1'; print join( "\n", sort keys %{ $hash_of_hash{ 'HASH1' } } )."\n"; print join( "\n", sort values %{ $hash_of_hash{ 'HASH1' } } )."\n"; | ||||||||||||||||||||||||||||
39) Reading complete file as one string |
my $filename = $0; #Name of current script flle my $rem_separater = $/; undef $/; open( FILE, $filename ) or die "Can not open $filename: $!\n"; my $complete_file = <FILE>; close( FILE ); $/ = $rem_separater; print $complete_file; | ||||||||||||||||||||||||||||
40) Using CGI module |
use CGI; my $query = new CGI; print "Content-type: text/html\n\n"; print $query->param( 'Textbox1' ); | ||||||||||||||||||||||||||||
41) Sending mail using Net::SMTP |
use Net::SMTP; my $smtp = Net::SMTP->new( $server ); die "SMTP not responding: $!\n" unless( $smtp ); $smtp->mail( $sender_id ); $smtp->to( $email_id ); $smtp->data(); $smtp->datasend("To: $email_id\n"); $smtp->datasend("From: $sender_id\n"); $smtp->datasend("Subject: $subject\n"); $smtp->datasend("\n"); $smtp->datasend("$body\n"); $smtp->dataend(); $smtp->quit; | ||||||||||||||||||||||||||||
42) Using Win32 module for MS Excelsheet |
use Win32::OLE qw(in with); use Win32::OLE::Const 'Microsoft Excel'; use Win32::OLE::Variant; use Win32::OLE::NLS qw(:LOCALE :DATE); $Win32::OLE::Warn = 3; # die on errors... my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit'); my $report_xls = 'test.xls'; my $Book = $Excel->Workbooks->Open( $report_xls ); my $Sheet = $Book->Worksheets( 'Sheet1' ); my ($row,$col) = (2,5); $Sheet->Cells($row,$col)->{'Value'} = "Cell ($row,$col) value"; $Sheet->Cells($row,$col)->Font->{ColorIndex} = 3; $Sheet->Cells($row,$col)->Interior->{ColorIndex} = 5; $Sheet->Cells($row,$col)->{HorizontalAlignment} = xlHAlignLeft; $Sheet->Cells($row,$col)->{VerticalAlignment} = xlVAlignTop; $Sheet->Cells($row,$col)->Font->{Name} = "Courier"; $Book->Save(); $Book->Close(); | ||||||||||||||||||||||||||||
43) Using Windows Semaphore |
require Win32::Semaphore; my $sema_name = 'semaphore-test'; my $sema_initial = 1; my $sema_maximum = 1; my $sema_wait_limit = 60; #seconds my $semaphore = Win32::Semaphore->new($sema_initial,$sema_maximum,$sema_name); my $wait_ret = $semaphore->wait( 1000 * $sema_wait_limit ); | ||||||||||||||||||||||||||||
44) Using CGI module for upload HTML form element for upload: "<input type=file name=attachment>" |
use CGI; use CGI::Carp qw ( fatalsToBrowser ); use File::Basename; my $attachment_size_limit = 5; #MB my $max_post_size = 1024 * 1000 * $attachment_size_limit + 1024; #1024 for actual request CGI::upload_hook(\&upload_hook); my $query = new CGI; print "Content-type: text/html\n\n"; my $filename = $query->param('attachment'); if( $filename ) { my $upload_filehandle = $query->upload('attachment'); my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' ); $filename = $name.$extension; $filename =~ s/[^\w|\-|\.]/_/g; open ( UPLOADATTACH, "> $local_filename" ) or exit; binmode UPLOADATTACH; while ( <$upload_filehandle> ) { print UPLOADATTACH; } close UPLOADATTACH; } sub upload_hook { my ($filename, $buffer, $bytes_read, $data) = @_; if( $bytes_read > $max_post_size ) { print 'Upload file size exceeds limit of '.$attachment_size_limit.' MB.<br><br>'; print 'Click <a href="#" onClick="history.go(-1)">here</a> to go back.<br><br>'; exit; } } | ||||||||||||||||||||||||||||
45) Modifier for regular expressions |
| ||||||||||||||||||||||||||||
46) Wildcards |
| ||||||||||||||||||||||||||||
47) Repetitions |
| ||||||||||||||||||||||||||||
48) Regularly used functions, operators |
|
© Copyright Samir Amberkar 2023-24