Get started !
online LTE test
online C test

Updated or New
Site traffic (Aug-15)
GMSK modulation
Case of frequency correction burst
Solving modulation equations
One bit change
Normal duration burst



About
Feedback
Information Theory
Modulation
Multiple Access
OSI Model
Data Link layer
SS7
Word about ATM
GSM
GPRS
UMTS
WiMAX
LTE
Standard Reference
Reference books
Resources on Web
Miscellaneous
Mind Map
Perl resources
Magic MSC tool
Bar graph tool
C programming
ASCII table
Project Management
Simple Google box
HTML characters
Site traffic
Page view counter
5 6 9 , 6 5 9
another knowledge site

Quick Perl Guide

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.

Comment Code 
1) Enforce variable declaration etc.   use strict;
 
2) Variable declaration   my $variable = 0;
 
3) Declare or define a HASH array   my %hash_array = (
     
      "KEY" => "VALUE",
      'Key' => 'Value'
 
  );
 
4) Declare or define a plain array   my @array = (
 
    'ELEMENT',
    'Element'
 
  );
 
5) Getting arguments to script   my $argument1 = $ARGV[0];
  die "Argument 1 not passed\n" unless( $argument1 );
 
6) Environment variables   my $env1 = $ENV{'ENV1'};
 
7) File operations - open, close   open( FILE, $input_file ) or
    die "Can not open $input_file: $!\n";
   
  while( <FILE> ) {
    chomp;
  }
  close( FILE );
 
8) Pattern matching   if( $variable =~ m/pattern/) {
    print "Pattern matched\n";
  }
 
9) Replacing pattern Globally and Ignoring case   my $pattern_replace_ctr =
    ($variable =~ s/pattern/replacewith/gi);
 
10) Access array element   print $plain_array[0];
 
11) Access hash array element   print $hash_array{ 'KEY' };
 
12) In loop   foreach my $element (@plain_array) {
    $element = 'new element';
  }
 
  foreach my $key (keys %hash_array) {
    $hash_array{ $key } = 'new value';
  }
 
13) Sorting alphabetically   my @sorted_array = sort @plain_array;
 
14) Sorting numerically   my @sorted_keys = sort { $a <=> $b } keys %hash_array;
 
15) Get (and remove) 1st element of an array   shift( @array );
 
16) Get (and remove) last element of an array   pop( @array );
 
17) Add an element at the beginning of an array UNSHIFT/SHIFT work like queue (FIFO)operations   unshift( @array, $element );
 
18) Add an element at the end of an array. PUSH/POP works like stack (LIFO) operations   push( @array, $element );
 
19) 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';
 
20) Array size   my $array_size = $#array; #Or
  my $array_size = SCALAR( @array );
 
21) Delete a key from hash array   delete $hash_array{ 'KEY' };
 
22) All values of hash   @values = values %hash_array;
 
23) Check if file exists   if ( -e $filename ) {
    print "File $filename exists.\n";
  }
 
24) Get filesize   my $filesize = -s $filename;
 
25) Check whether directory   if( -d $filename ) {
    print "$filename is directory.\n";
  }
 
26) 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";
  }
 
27) Rename the file   rename( $filename, $new_filename );
 
28) Deleting file   unlink( $filename );
 
29) Copying file   use File::Copy;
  copy( $filename, $copy_of_filename );
 
30) 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 );
 
31) 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 );
 
32) Executing system command   system( $command );
 
33) Functions   sub test_function {
    my ($param1, $param2) = @_;
 
    my ($out1, $out2);
 
    return ($out1, $out2);
  }
 
34) 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";
 
35) 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";
 
36) 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";
 
37) 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";
 
38) 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;
 
39) Using CGI module   use CGI;
  my $query = new CGI;
  print "Content-type: text/html\n\n";
  print $query->param( 'Textbox1' );
 
40) 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;
 
41) 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();
 
42) 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 );
 
43) 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;
    }
  }
 

Modifier for regular expressions

g Match globally
i Ignore case
s '.' matches newline

Wildcards

. Match any character except newline unless /s modifier used
\w Alphanumeric
\W Non-alphanumeric
\s Any white-space character (Space, Tab, Newline)
\d Digit
\D Non-digit
\t Tab
\n Newline
\r Return
\f Formfeed
\a Alarm
\e Escape
\b Word boundary
\B non-Word boundary

Repetitions

* Match 0 or more
+ 1 or more
? 0 or 1 but not more
{n} Exactly n times
{n,} At least n times
{m,n} Least m, maximum n times

References: Programming Perl by Larry Wall et al.

Copyright © Samir Amberkar 2010§