Emidio Planamente 's Homepage

Home GNU/Linux Programming Technology Sport Others Contact

C++ (and C)

  Boost (Smart Pointers)
  C++ Reference
  C++ Resources
  Dinkumware
  Reference Guide


Html


MySql

  Freaks
  Manual


Perl

  Perl 4
  Perl 5
  Perldoc


Php

  Freaks
  Php


Shell

  ABS
  Bash Reference


HTML validator CSS validator

 

Programming in Perl

C++

Html

MySQL

Perl

Php

Shell


1. Arguments

2. Array

3. Codes

4. Commands

5. Hash

6. File

7. Function

8. Operator

9. Pattern matching

10. Processes

11. String

12. Tricks


1. Arguments


1.1. Getting arguments


The allowed parameters are listed calling getopts().

If the parameter is followed by ':', a supplementary argument is required.


  use Getopt::Std;

  my %switch = ();

  getopts("a:dhv", \%switch);

  if($switch{a})

  {

    print "Called with switch -a $switch{a}\n";

  }

  elsif($switch{d})

  {

    print "Called with switch -d\n";

  }

  elsif($switch{h})

  {

    print "Called with switch -h\n";

  }

  elsif($switch{v})

  {

    print "Called with switch -v\n";

  }

  else

  {

    my $base=`/usr/bin/basename $0`; chomp $base;

    print "ERROR: wrong arguments. Type $base -h for help\n";

  }


Possible calls:


  myScript

  ERROR: wrong arguments. Type myScript -h for help


  myScript -h

  Called with switch -h


  myScript -d

  Called with switch -d


  myScript -v

  Called with switch -v


  myScript -a

  ERROR: wrong arguments. Type myScript -h for help

  myScript -a Hello

  Called with switch -a Hello


2. Array


2.1. Creating array


  @array = ("one", "two", "tree");


2.2. Adding value to array


  push(@array, "four");


2.3. Getting length of an array


Number of elements:


  scalar(@array);


Index of last element:


  #@array


Value of an element:


  $array[3];


Note that in this case the variable @array is used with the $ symbol and not with the @ symbol. This because only one element is returned from this call.


2.4. Grepping in an array


The following examples list in @match all the lines containing the words stored either in $keyword or @keywords.


  my @match = grep { /$keyword/ } @array;


  my @match = grep { /@keywords/ } $variable;


  my @match = grep { /@keywords/ } @array;


2.5. Sorting an array


  my @sorted = sort { $a <=> $b } @input;


Note that this doesn't work:


  my @sorted = sort @input;


2.6. Sorting an array with unique elements


Perl doesn't provide such a functionality, therefore you must implement it your self.


Here a working example:


  %seen = ();

  @array_unique = ();

  foreach $item (@array_not_unique)

  {

    unless($seen{$item})

    {

      # element not stored yet

      $seen{$item} = 1;

      push(@array_unique, $item);

    }

  }


3. Codes


3.1. Code matches


  \a  Alarm (beep)

  \n  Newline

  \r  Carriage return

  \t  Tab

  \f  Formfeed

  \e  Escape

  \d  A digit, same as [0-9]

  \D  A nondigit

  \w  A word character (alphanumeric), same as [a-zA-Z_0-9]

  \W  A nonword character

  \s  A whitespace character, same as [ \t\n\r\f]

  \S  A non-whitespace character


3.2. Assertion meaning


  ^   Matches at the beginning of the string (or line, if /m used)

  $   Matches at the end of the string (or line, if /m used)

  \b  Matches at word boundary (between \w and \W)

  \B  Matches except at word boundary

  \A  Matches at the beginning of the string

  \Z  Matches at the end of the string

  \G  Matches where previous m//g left off

  (?=...) Matches if engine would match ... next

  (?!...) Matches if engine wouldn't match ... next


3.3. Maximal minimal allowed range


  {n,m}{n,m}?  Must occur at least n times but no more than m times

  {n,}{n,}?    Must occur at least n times

  {n}{n}?      Must match exactly n times

  **?          0 or more times (same as {0,})

  ++?          1 or more times (same as {1,})

  ???          0 or 1 time (same as {0,1})


4. Commands


4.1. Command grep


The following examples list in @match all the lines containing

the words stored either in $keyword or @keywords.


  my @match = grep { /$keyword/ } @array;


  my @match = grep { /@keywords/ } $variable;


  my @match = grep { /@keywords/ } @array;


5. Hash


5.1. Creating a hash


  %hash = ("first index" => "first element",

          "second index" => "second element"

         );


5.2. Adding value to a hash


  $hash{$key} = $value;


5.3. Getting length of a hash


This returns the numbers of keys in the hash (0 = hash is empty):


  scalar(keys(%hash));


6. File


6.1. Opening file


  my $file = "MyFile";

  open(FILE, "<$file") or die "ERROR: unable to open $file: $!";

  close(FILE);


List of open modes:


  Filename Read Write Append Create Trunc O_flags             Char


   <file   yes   no     no     no     no   RDONLY              "r"

   >file   no    yes    no     yes    yes  WRONLY TRUNC CREAT  "w"

  >>file   no    yes    yes    yes    no   WRONLY APPEND CREAT "a"

  +<file   yes   yes    no     no     no   RDWR                "r+"

  +>file   yes   yes    no     yes    yes  RDWR TRUNC CREAT    "w+"

  +>>file  yes   yes    yes    yes    no   RDWR APPEND CREAT   "a+"


  open(FH, "filename");               # read from existing file

  open(FH, "<filename");              # read from existing file (explicitly)

  open(FH, ">filename");              # create file and write to it

  open(FH, ">>filename");             # append to existing file

  open(FH, "| output-pipe-command");  # set up an output filter

  open(FH, "input-pipe-command |");   # set up an input filter


6.2. Reading file line by line


  my $file = "MyFile";

  open(FILE, "<$file") or die "ERROR: unable to open $file: $!";

  while(<FILE>)

  {

    my $line = $_;

    print STDOUT $line;

  }

  close(FILE);


6.3. Reading a specific line


  $. = 0;

  do

  {

    $line = <HANDLE>

  }

  until $. == $DESIRED_LINE_NUMBER || eof;


or put file content in an array:


  @lines = <HANDLE>;

  $LINE = $lines[$DESIRED_LINE_NUMBER];


6.4. Reading configuration file


  eval `cat $config`;


6.5. Creating temporary file


  use IO::File;

  $fh = IO::File->new_tmpfile or die "Unable to make new temporary file: $!";


6.6. Renaming a file


  rename($old_filename, $new_filename) or die "can't rename $old_filename to $new_filename: $!";


6.7. Deleting a file


  unlink($FILENAME) or die "Can't delete $FILENAME: $!\n";


For more files:


  unlink(@FILENAMES) == @FILENAMES  or die "Couldn't unlink all of @FILENAMES: $!\n";


6.8. Copying a file


  use File::Copy;

  copy($oldfile, $newfile);


6.9. Locking a file


Call flock() before writing to a file:


  open(FILE, "+< $file") or die "can't open $file: $!";

  flock(FILE, 2) or die "can't flock $path: $!";

  # make something with $file

  close(FH)



List of lock modes:


  1  Shared lock (for reading)

  2  Exclusive lock (for writing)

  4  Non-blocking request (don't stall)

  8  Free the lock (careful!)


6.10. Getting all files in a directory


  opendir(DIR, $dirname) or die "can't opendir $dirname: $!";

  while (defined($file = readdir(DIR)))

  {

    push(@file, "$dirname/$file");

  }

  closedir(DIR);


6.11. Getting all files in a directory with filename expansions


Get files like a shell would do.


  @file = glob("*.txt");

  @file = map { glob($_) } "*.c", "*.c,v";

  @file = map <${_}>, "*.c", "*.c,v";


6.12. Splitting filename


  use File::Basename;


  $base = basename($path);

  $dir  = dirname($path);

  ($base, $dir, $ext) = fileparse($path);


6.13. Flushing output


If the output doesn't appear immediately, disable buffering:


  $old_fh = select(OUTPUT_HANDLE);

  $| = 1;

  select($old_fh);


or


  use IO::Handle;

  OUTPUT_HANDLE->autoflush(1);


6.14. Getting file or directory properties


  @entry = stat($file) or die "Couldn't stat $file: $!";


List of properties:


   Element Abbreviation Description


   0       dev          Device number of filesystem

   1       ino          Inode number (the "pointer" field)

   2       mode         File mode (type and permissions)

   3       nlink        Number of (hard) links to the file

   4       uid          Numeric user ID of file's owner

   5       gid          Numeric group ID of file's owner

   6       rdev         The device identifier (special files only)

   7       size         Total size of file, in bytes

   8       atime        Last access time, in seconds, since the Epoch

   9       mtime        Last modify time, in seconds, since the Epoch

  10       ctime        Inode change time, in seconds, since the Epoch

  11       blksize      Preferred block size for filesystem I/O

  12       blocks       Actual number of blocks allocated


Example:


  use File::stat;

  $file = "/bin/ls";

  $inode = stat($file);

  $ctime = $inode->ctime;

  $size  = $inode->size;


6.15. Accessing files and printing output at the same time


Once opened a file, the print command redirect all to the opened file. To redirect some messages to the screen, use the following command:


  SELECT STDOUT;


and to redirect to the opened file:


  SELECT YOUR_FILE_HANDLER;


A much better possibility is to specify always where to redirect the datas:


  print FILEHANDLER "This is written into the file\n";

  print STDOUT "This is written to the screen\n";


6.16. Passing file handler to a function


  my $file = "myFile.txt";

  open(FH, "<$file") or die "ERROR: unable to open $file: $!\n";

  myFunction(*FH);

  close (FH);


  sub myFunction($)

  {

    local *FH = $_[0];

    print FH "Hello\n";

  }


7. Function


7.1. Calling a function reading its name from a variable


  $func = (caller[0][3])


8. Operator


8.1. Arithmetic operators


  EXAMPLE    NAME             RESULT


  $a + $b    Addition         Sum of $a and $b

  $a * $b    Multiplication   Product of $a and $b

  $a % $b    Modulus          Remainder of $a divided by $b

  $a ** $b   Exponentiation   $a to the power of $b


8.2. Comparison operators


  COMPARISON          NUMERIC  STRING   RETURN VALUE


  Equal               ==       eq       True if $a is equal to $b

  Not equal           !=       ne       True if $a is not equal to $b

  Less than           <        lt       True if $a is less than $b

  Greater than        >        gt       True if $a is greater than $b

  Less than or equal  <=       le       True if $a not greater than $b

  Comparison          <=>      cmp      0 if equal, 1 if $a greater, -1 if $b greater


8.3. File test operators


  EXAMPLE  NAME         RESULT


  -e $a    Exists       True if file named in $a exists

  -r $a    Readable     True if file named in $a is readable

  -w $a    Writable     True if file named in $a is writable

  -d $a    Directory    True if file named in $a is a directory

  -f $a    File         True if file named in $a is a regular file

  -T $a    Text File    True if file named in $a is a text file


8.4. Logical operators


  EXAMPLE     NAME     RESULT

  $a && $b    and      $a if $a is false, $b otherwise

  $a and $b   and      $a if $a is false, $b otherwise

  $a || $b    or       $a if $a is true, $b otherwise

  $a or $b    or       $a if $a is true, $b otherwise

  ! $a        not      True if $a is not true

  not $a      not      True if $a is not true


8.5. String operators


  $a = 1;

  $b = 2;

  print $a + $b;     # prints 3

  print $a . $b;     # prints 12

  print $a x $b;     # prints 11 (2 times the "1")


All the following exmaples give the same result:


  print $a . ' is equal to ' . $b . "\n";    # dot operator

  print $a, ' is equal to ', $b, "\n";       # list

  print "$a is equal to $b\n";               # interpolation


9. Pattern matching


9.1. Assertions


  ASSERTION    MEANING


  ^            Matches at the beginning of the string (or line, if /m used)

  $            Matches at the end of the string (or line, if /m used)

  \b           Matches at word boundary (between \w and \W)

  \B           Matches except at word boundary

  \A           Matches at the beginning of the string

  \Z           Matches at the end of the string

  \G           Matches where previous m//g left off

  (?=...)      Matches if engine would match ... next

  (?!...)      Matches if engine wouldn't match ... next


9.2. Modifiers


  MODIFIER    MEANING


  g           Match globally, i.e., find all occurrences

  i           Do case-insensitive pattern matching

  m           Treat string as multiple lines

  o           Only compile pattern once

  s           Treat string as single line

  x           Extend your pattern's legibility with whitespace and comments


Example:


  m/Hello/i


9.3. Special characters


  CODE    MATCHES


  \a      Alarm (beep)

  \n      Newline

  \r      Carriage return

  \t      Tab

  \f      Formfeed

  \e      Escape

  \d      A digit, same as [0-9]

  \D      A nondigit

  \w      A word character (alphanumeric), same as [a-zA-Z_0-9]

  \W      A nonword character

  \s      A whitespace character, same as [ \t\n\r\f]

  \S      A non-whitespace character


9.4. Quantifiers


  MAXIMAL MINIMAL  ALLOWED RANGE


  {n,m}   {n,m}?   Must occur at least n times but no more than m times

  {n,}    {n,}?    Must occur at least n times

  {n}     {n}?     Must match exactly n times

  *       *?       0 or more times (same as {0,})

  +       +?       1 or more times (same as {1,})

  ?       ??       0 or 1 time (same as {0,1})


10. Processes


10.1. Reading from a program


  my $program = "ls -al";

  $pid = open(PH, "$program |" or die "ERROR: unable to open $program: $!\n";

  while(<PH>)

  {

    print STDOUT $_;

  }

  close(PH);


10.2. Writing to a program


  my $program = "echo -n";

  $pid = open(PH, "| $program" or die "ERROR: unable to open $program: $!\n";

  print PH "hello\n";

  close(PH);


11. String


11.1. Accessing substring


  $value = substr($string, $offset, $count);

  $value = substr($string, $offset);


To extract the last character(s):


  $last = substr($string, -1);

  $piece = substr($string, -8, 3);


11.2. Accessing colomns


Forward 6, grab 2, backward 5, grab 2


  ($b, $c) = unpack("x6 A2 X5 A2", $a);


11.3. Accessing one character at time


  @array = split(//, $string);


  foreach my $c(@array)

  {

    # make something with $c

  }


11.4. Comparing strings


Strings must be exactly the same:


  if($date eq "2004-01-01")

  {

    print "Today is a new year!\n";

  }


String A must contain string B:


  if($stringA =~ /$stringB/)

  {

  }


11.5. Converting TABS to spaces and viceversa


Possibility 1:


  while ($string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e)

  {

    # spin in empty loop until substitution finally fails

  }


Possibility 2:


  use Text::Tabs;

  $tabstop = 8;  # number of spaces

  @expanded_lines  = expand(@lines_with_tabs);

  @tabulated_lines = unexpand(@lines_without_tabs);


11.6. Controlling case


Convert to uppercase:


  uc($string);


  $string = "\Uabc";


  ucfirst =^ \u (???)


Convert to lowercase:


  lc($string);


  $string = "\LABC";


  lcfirst =^ \l (???)


12. Tricks


12.1. Swapping variables


  $a       = "alpha";

  $b       = "omega";

  ($a, $b) = ($b, $a);


12.2. Converting ascii to integer and viceversa


  $num  = ord($char);

  $char = chr($num);


  $char = sprintf("%c", $num);

  printf("Number %d is character %c\n", $num, $num);


12.3. Simple if


  $ok ? "STDOUT" : "STDERR";


12.4. Simple repeat character


  $separator = "-" x 80;


12.5. Replacing characters and copy the result in a new variable


  ($a = $b) =~ s/xxx//;


  Same as


  $a = $b; $a =~ s/xxx//;


12.6. Working with directories


  chdir

  updir

  curdir


12.7. Environment variables


This should return /home/username


  $ENV{HOME}


12.8. Getting the script directory


  use FindBin qw($Bin);

  my $SCRIPT_PATH = $Bin;


12.9. Executing shell script


12.9.1. Using apostrophe


The first possibility is:


  `mkdir /test/`


12.9.2. Using "System" call


The second possibility is:


  !system("mkdir /test") or die "ERROR: unable to create /test\n";


Note the \n at the end of the line. This will not print at what line the script has been stopped.

Instead, in this case


  !system("mkdir /test") or die "ERROR: unable to create /test. Aborting ";


the error message will be


  ERROR: unable to create /test. Aborting at line bla bla bla.


12.9.3. Using pipe


Use open with a pipe like:


  open(HANDLER, "your system command here |");

  while(<HANDLER>)

  close HANDLER;


The following example prints all the files present in /tmp having "txt" as extension:


  open (HANDLER, "find /tmp -name \"*.txt\" |");

  while (<HANDLER>)

  {

    print $_;

  }

  close HANDLER;



C++

Html

MySQL

Perl

Php

Shell


Emidio Planamente

Last modified on 2024-08-02