Thursday, November 17, 2011

How to pass optional parameters to a Perl function?

You can use a semicolon in the prototype to indicate the end of the required parameters:

sub someFunction($$;$) {
  my ( $oblig_param1, $oblig_param2, $option_param ) = @_;
  ...
}
 
The ; is optional before a @ or %, which, according to the docs, "gobbles up everything else".

How do I get a file's last modified time in Perl?

You can use the built-in module File::stat (included as of Perl 5.004).
Calling stat($fh) returns an array with the following information about the file handle passed in (from the perlfunc man page for stat):

  0 dev      device number of filesystem
  1 ino      inode number
  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 since the epoch
  9 mtime    last modify time since the epoch
 10 ctime    inode change time (NOT creation time!) since the epoch
 11 blksize  preferred block size for file system I/O
 12 blocks   actual number of blocks allocated

The 9th element in this array will give you the last modified time since the epoch (00:00 January 1, 1970 GMT). From that you can determine the local time:

my $epoch_timestamp = (stat($fh))[9];
my $timestamp       = localtime($epoch_timestamp);
 
To avoid the magic number 9 needed in the previous example, additionally use Time::localtime, another built-in module (also included as of Perl 5.004). This requires some (arguably) more legible code:

use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);

Monday, November 7, 2011

Perl & MySQL


Perl & MySQL help. Here we will give some help on some common issues with regard to MySQL database access from within your Perl programs.

Requirements: Perl 5 (preferably the latest production release), Perl DBI (downloadable from CPAN), DBD::mysql (see CPAN) and MySQL database server.

Simple script that illustrates how to connect to a MySQL database and issues a range of select, delete and update queries:

#! /usr/bin/perl -wT

use strict;
use DBI;

$ENV{PATH} = "/bin:/usr/bin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};


# we assume that the name of your database is DATABASE, that the username 
# to connect is UN and the password is PW. Here we also assume that your 
# MySQL server is running on localhost (so your are connecting through 
# the Unix socket file).

my $dbh = DBI->connect('DBI:mysql:DATABASE:localhost', 'USERNAME', 'PASSWORD')
  or die "Cannot connect: " . $DBI::errstr;

# or:

my $dbh = DBI->connect('DBI:mysql:database=DATABASE;host=localhost','USERNAME','PASSWORD')
  or die "Cannot connect: " . $DBI::errstr;


# select a single field:

my $sql = qq`SELECT field FROM table WHERE otherfield=1`;
my $sth = $dbh->prepare($sql) or die "Cannot prepare: " . $dbh->errstr();
$sth->execute() or die "Cannot execute: " . $sth->errstr();
my $field = $sth->fetchrow_array();
$sth->finish();

print "field is $field \n";


# select multiple fields:

$sql = qq`SELECT fielda,fieldb,fieldc FROM table WHERE otherfield=1`;
$sth = $dbh->prepare($sql) or die "Cannot prepare: " . $dbh->errstr();
$sth->execute() or die "Cannot execute: " . $sth->errstr();
my ($fielda,$fieldb,$fieldc) = $sth->fetchrow_array();
$sth->finish();

print "fielda is $fielda , fieldb is $fieldb , fieldc is $fieldc \n";


# select multiple fields with multiple rows:

$sql = qq`SELECT fielda,fieldb,fieldc FROM table`;
$sth = $dbh->prepare($sql) or die "Cannot prepare: " . $dbh->errstr();
$sth->execute() or die "Cannot execute: " . $sth->errstr();
my @row;
my @fields;
while(@row = $sth->fetchrow_array()) {
  my @record = @row;
  push(@fields, \@record);
}
$sth->finish();


# now process the fields

if (@fields != 0) {
  my $i=0;
  foreach $line (@fields) {
    print "row $i - a is @$line[0] , b is @$line[1] , c is @$line[2] \n";
    $i++;
  }
}


# delete query

$sql = qq`DELETE FROM table WHERE field=1`;
$sth = $dbh->prepare($sql) or die "Cannot prepare: " . $dbh->errstr();
$sth->execute() or die "Cannot execute: " . $sth->errstr();
$sth->finish();


# update query

$sql = qq`UPDATE table SET field=1 WHERE otherfield=2`;
$sth = $dbh->prepare($sql) or die "Cannot prepare: " . $dbh->errstr();
$sth->execute() or die "Cannot execute: " . $sth->errstr();
$sth->finish();


# To increase your application security and prevent SQL injection attacks,
# it is advisable to use placeholders in queries (prepared statements):

$sql = qq`SELECT field FROM table WHERE name=? AND password=?`;
$sth = $dbh->prepare($sql) or die "Cannot prepare: " . $dbh->errstr();
$sth->execute($name, $password) or die "Cannot execute: " . $sth->errstr();
my $field = $sth->fetchrow_array();
$sth->finish();
  

Sorting Techniques perl

e. Moving to the meat of the matter staight away, we'll start from talking about comparison. Obviously, in order to put a list of things in order, you'll have to first define that order. Order is defined by how things compare to each other. If I give you two items from the list, can you tell me which one is bigger / better / nicer / sexier ... [insert you favourite adjective here] than the other? Or tell me thet they are both of equal order? Well, that's just about it! If you give me a list of items and promise me that you can answer this question for any pair of them, I can make a sorted list of them. All I have to do is take all possible pairs and ask you "how do these two compare?" and arrange them accordingly to finally come up with a sorted list. Actually there are even smarter ways to do it, minimising the amount of comparisons needed, but that is not an issue here, as we will see soon that perl performs that task for us, and we trust perl that it uses the least expensive method. Now, the issue in question being comparison, I assume you must be familiar with all (or at least most) of perl's comparison operators. There's a list of them:


Numbers Strings
< lt
> gt
<= le
>= gr
== eq
<=> cmp

Now the first five rows should be ok, they're just like math. But what are the <=> and cmp operators? Basically, the expression $a <=> $b (or $a cmp $b for strings) returns one of the values 1, 0, -1 if $a is, respectively, larger, equal or lower than $b. (see table below)

Relation of $a and $b Value Returned by $a <=>
$a greater than $b 1
$a equal to $b 0
$a less than $b -1

Does that ring a bell? Coming to think of it, the <=> and cmp operators actually provide the answer to the question we were investigating earlier when we talked about how to sort by using a comparative criterion. So, if we already have an operator that answers this question ("how do two items compare?") all we need is a function that will take a list of items and perform the necessary comparisons to arrive at a sorted list. And guess what? That's exactly what perl's sort operator does. So, if you have an unsorted list @not_sorted and want to created a sorted list @sorted, you just say: @sorted = sort { $a <=> $b } @not_sorted # numerical sort or @sorted = sort { $a cmp $b } @not_sorted # ASCII-betical sort or better @sorted = sort { lc($a) cmp lc($b) } @not_sorted # alphabetical sort Looking at the sort function, we notice that it is exactly as we described it in words, earlier in this article. Perl needs just two things: the list of items to sort, and a subroutine that answers the question "how do these two compare?" for any pair of items in the list. Perl puts the two items it want to compare int the special variables $a and $b and your function is responsible to give a return value that corresponds to the existing relationship of the two, as shown in the table shown earlier. Here, in this simple example, we used perl's built-in comparison operators that work for numerical and alphabetical (not realy... to be correct it is ASCII order) sorting. Of course, you can roll your own comparison function to create sorts for any kind of ordering you wish to have. Before you start coding your own functions, take a look to the following examples:

Get a list of hash keys sorted by value.

@sorted = sort { $hash{$a} cmp $hash{$b} } keys %hash;

Get a reverse sort of a list.

@sorted = sort { $b cmp $a } @list; Which can also be done with @sorted = reverse sort { $a cmp $b } @list;

Get an alphabetical sort of words, but make 'aardvark' always come last.

(Now, why you would want to do that is another question...) @sorted = sort { if ($a eq 'aardvark') { return 1; } elsif ($b eq 'aardvark') { return -1; } else { return $a cmp $b; } } @words;

Quick Start Perl

Perl is about saving time. In just 20 minutes, this short introduction to Perl will show you enough to start using Perl straight away. Your new Perl knowledge may save you 20 minutes of work today... so you'll be even. Tomorrow it may save you 20 minutes more.
Read from top to bottom. Leave out nothing, the tutorial is cumulative. Read the example code too, it holds many important insights.

Topics

These links are useful for reference. Read the whole tutorial the first time.

  Scalar Variables
  Logic and Truth
  Arrays and Hashes
  Command Line Arguments
  Conditions
  Files
  Pattern Matching
  Regular Expressions
  Groups
  Netlist Filtering

Scalar Variables

Scalar variables have no explicit type. Scalar variables do not have to be declared. Context is very important in Perl. Mathematical operators treat variables as numbers, integers or floating point, depending on the context. String operators treat variables as strings of characters. Conversion between strings and numbers is automatic. Everything in Perl behaves in the most obvious common-sense way. Perl is very intuitive.
Here are some scalar variables and some numeric operators:

# End of line comments begin with a #

$a = 17;      # Scalar variables begin with a dollar symbol
              # The Perl assigment operator is =
              # Statements finish with a semicolon ;

$b = 0x11;    # Hexadecimal (17 in decimal)
$c = 021;     # Octal       (17 in decimal)
$d = 0b10001; # Binary      (17 in decimal)
$f = 3.142;   # Floating point

$a = $a + 1;  # Add 1 to variable $a
$a += 1;      # Add 1 to variable $a
$a++;         # Add 1 to variable $a

$b = $b * 10; # Multiply variable $b by 10;
$b *= 10;     # Multiply variable $b by 10;

              # Other arithmetic operators include:
              #  **  Exponentiation
              #  %   Modulo division
              #  ++  Auto increment
              #  --  Auto decrement
              #  <   Numeric less than
              #  >   Numeric greater than
              #  ==  Numeric equality
              #  !=  Numeric inequality
              #  <=  Numeric less than or equal to
              #  >=  Numeric greater than or equal to
              #  <=> Numeric compare: Returns -1 0 1

Scalar variables can store strings of characters or words. Single quotes, 'like these', allow spaces to appear inside strings. Double quotes, "like these", allow variables to be automatically substituted or interpolated inside strings.

$a = 'Number of DFFs: '; # No interpolation with 'single quotes'
$b = "$a$c\n";           # Interpolation (variable substitution) with "double quotes"
                         # \n is the newline character
print $b;                # This makes "Number of DFFs: 17\n" appear on the standard output
print $a, $c, "\n";      # As does this line because print takes
                         #    a comma separated list of arguments to print
print "That's all\n";    # No commas means a list of one element

                         # String operators include:
                         #  lt  String less than
                         #  gt  String greater than
                         #  le  String less than or equal to
                         #  ge  String greater than or equal to
                         #  cmp String compare: Returns -1 0 1
print 'one' lt 'two';    # Prints 1
                         #    ASCII-betically 'o' is less than 't'
print 'buf4' lt 'buf3';  # Prints nothing (that is undef, numerically zero)
                         # Perl's undefined value is undef
                         #    ASCII-betically '4' is not less than '3'

Logic and Truth

Perl considers these to be false:
0;      # Integer zero
  0.0;    # Decimal zero
  '0';    # String containing a single zero character
  '';     # Empty string
  undef;  # Undefined
Everything else is true.   Here are some logical operators:

$a = 0; $b = 45;      # More than one statement per line possible
print( $a and $b++ ); # prints 0        *
$a = 22;
print( $a and $b++ ); # prints 45       *
print $b;             # prints 46
                      # *  $b++ only evaluated when $a was true
                      # Some logic operators take shortcuts

                      # Other logical operators include
                      # or  Logical OR
                      # ||  Logical OR
                      # and Logical AND
                      # &&  Logical AND
                      # not Logical NOT
                      # !   Logical NOT
                      # |   Bitwise OR
                      # &   Bitwise AND
                      # ~   Bitwise NOT

print 6 & 5;          # prints 4, 0b0110 & 0b0101 = 0b0100
print 6 | 5;          # prints 7, 0b0110 | 0b0101 = 0b0111
print ! 0;            # prints 1
print ! 5;            # prints nothing (that is undef or false)
print ~5;             # prints 4294967290, same as:
                      # 0b11111111111111111111111111111010

Arrays and Hashes

An array is a list of scalar variables. The first element has index 0. The @ symbol is used to denote an array variable.
@components = ( 'X_LUT4', 'X_AND2', 'X_BUFGMUX', 'X_BUF_PP', 'X_FF' );

# or use qw''. Saves typing commas or quotes, gives the same result
# qw stands for Quoted Words
@components = qw'X_LUT4 X_AND2 X_BUFGMUX X_BUF_PP X_FF';

# or even put the data in columns, gives the same result again
@components = qw'
                    X_LUT4
                    X_AND2
                    X_BUFGMUX
                    X_BUF_PP
                    X_FF
                ';             # Easier to read this way

push( @components, 'X_MUX2' ); # Push another item onto the top
push( @components, 'X_ONE' );  # And one more

print $components[0];          # Prints element 0, that is, 'X_LUT4'
print $components[5];          # Prints element 5, that is, 'X_MUX2'

print "@components\n";         # Prints everything separated by spaces:
# X_LUT4 X_AND2 X_BUFGMUX X_BUF_PP X_FF X_MUX2 X_ONE

print  @components   ;         # No double quotes, no spaces:
# X_LUT4X_AND2X_BUFGMUXX_BUF_PPX_FFX_MUX2X_ONE

In a scalar context an array variable returns its size, the number of elements it contains. The test expression of a while loop is tested for true or false, a scalar question, a scalar context. The shift statement removes items from the bottom of the array, one at a time.
while( @components ) {
#     ^^^^^^^^^^^^^                       Array in scalar context
  $next_component = shift( @components );
  print "$next_component\n";
}
# Array variable @components is now empty
In this example @components begins with size 7, which is true. After 7 loops each of the 7 elements have been shifted or removed from the bottom of the array. In the while test expression @components would have returned 7, 6, 5, 4, 3, 2, 1 and finally 0. Zero is false, end of while loop.
Hash arrays differ from arrays because the elements are not ordered numerically but associated with unique strings or keys. Hash arrays are associative arrays because they associate values with keys. Maintaining many separate counters is a good hash array application as we will see later. Hashes make a big contribution to Perl's text processing power. The % symbol is used to denote a hash array.

# Initialising several hash keys
%components = qw'
                  X_LUT4     0
                  X_AND2     0
                  X_BUFGMUX  0
                  X_BUF_PP   0
                  X_FF       0
                ';
#                 ^^^^^^^^^        keys
#                            ^   values
$components{'X_LUT4'} = 1; # Set key X_LUT4 to the value 1
$components{'X_LUT4'}++;   # Increment value associated with X_LUT4
print $components{'X_FF'}; # Print value associated with X_FF
@keys = keys %components;  # Get a list of hash keys
print "@keys\n";           # Print them - order is indeterminate
%components = ();          # Emptying the components hash

Command Line Arguments

There is a special array called @ARGV. Command line arguments are automatically copied into this array variable.
# This script is called process_netlist.pl
# Perl scripts often have the file extension .pl

$netlist_filename = $ARGV[0];
$report_filename  = $ARGV[1];
print "    Processing $netlist_filename\n";
print "    Writing report to $report_filename\n";
print "    ARGV contains '@ARGV'\n";

# Use it in this way:

#    C:\perl process_netlist.pl chip_timesim.vhd report.txt
#        Processing chip_timesim.vhd
#        Writing report to report.txt
#        ARGV contains 'chip_timesim.vhd report.txt'
#    C:\


Conditions

Perl has many conditional statements. The if statement asks a true/false question. If the answer is true it executes a block of code.
if( $ff_count == 1 )
#   ^^^^^^^^^^^^^^ Is this expression true or false?
{
  # Do this action if it is true
  print "There is 1 flip flop\n";
}
else
{
  # Do this action if it is false
  print "There are $ff_count flip flops\n";
}

# More compact layout
if( $ff_count == 1 ) {
  print "There is 1 flip flop\n";
} else {
  print "There are $ff_count flip flops\n";
}
It is not necessary to have an else part. The (round brackets) are required around the expression. The {curly brackets} are required around the actions.
The while loop repeatedly executes a block of statements while a conditional expression is true.
# Counting to one hundred
while( $count < 100 ) {
  $count++;             # Perl assumes $count == 0 the first time
  print "$count\n";
}
Variables do not have to be declared or initialised. Perl will create the variable when it is first used. If the variable is first used in a numeric context then its undefined initial value will be interpreted as zero. If the variable is first used in a string context then its undefined initial value will be interpreted as an empty string. Perl's default behaviour makes good sense. Counting begins at zero. Writing begins with an blank page.
Another loop statement is foreach. It is used for looping through a list of scalars, numeric or string.


foreach $course ( 'VHDL', 'SystemVerilog', 'SystemC', 'Perl', 'Tcl/Tk', 'PSL' ) {
  print "There is a $course Doulos training course\n";
}
# $course is the loop variable.
# It takes the string value 'VHDL' for the first loop
# and 'PSL' for the last loop.

# Get a list from an array variable
foreach $component ( @components ) {
  print "Component is $component\n";
}

Files

Text files are created with the open and print statements. Perl uses file handles to refer to each open file. A file handle is just a string, conventionally written in uppercase letters without quotes. Use the print statement to write text into a file.
open( FILE1, '>file1.txt' );
#             ^                               > means open in write mode
print FILE1 "The first line to file1.txt\n";
print FILE1 "The final line to file1.txt\n";
close( FILE1 );                               # Don't have to explicitly close a file

print STDOUT "This goes to the standard output\n";
print        "So does this\n";
#     ^^^^^^    STDOUT is a file handle that always
#               refers to the standard output.
#               It is the default so doesn't have to be stated.
Text files are read using the open statement and the input record operator.   Standard input, the input typed into the keyboard in a command line application, can be read from the STDIN file handle.

open( FILE2, 'file2.txt' );  # Open in read mode - the default mode
$first_line = <FILE2>;       # Reads the first line from file2.txt into $first_line.
                             # Includes the newline character, \n.
while( $line = <FILE2> ) {
  print $line;               # Read and print remaining lines from file2.txt.
}                            # When every line has been read <FILE2> returns undef.

$standard_input = <STDIN>;   # Read a line from the standard input.
                             # Can be the keyboard if run from the command line.

chomp( $standard_input );    # Remove the trailing newline character

Here is a short program. It reads every line from a file named in the first command line argument. The lines are written to a report file named in the second command line argument. Numbers are printed at the beginning of each line.
$netlist_filename = $ARGV[0];
$report_filename  = $ARGV[1];
open( FILE_IN, $netlist_filename );
open( FILE_OUT, ">$report_filename" );
while( $line = <FILE_IN> ) {
  $line_count++;
  print FILE_OUT "$line_count: $line";
}
# perl filter_netlist.pl chip_timesim.vhd report.txt

This Perl script does the same using standard input and standard output.

while( $line = <STDIN> ) {
  $line_count++;
  print "$line_count: $line";
}
# perl filter_netlist.pl < chip_timesim.vhd > report.txt

Pattern Matching

Perl's matching operator uses regular expressions to search a string for a match. Regular expressions are patterns used to find a match for a string of characters contained in a longer string. Regular expressions are built from character classes. The simplest character class is a single character. The letter A matches a capital letter A once. Character classes only match one character but the character can be any from a list of qualifying characters.

$string = "Novice to Expert in a 3 day Perl course.\n";
print $string;
if( $string =~ m/Expert/ ) {
  # A successful match returns 1 so this statement is executed
  print "This string contains the substring 'Expert'\n";
}
# m stands for match
# Forward slashes are used to /delimit/ regular expressions.
# =~ tells the m operator which string to search.
# The m is optional when // are used.

Regular Expressions

Individual letters are very limited character classes. Ranges of characters are matched using character class shortcuts. Any alphanumeric character matches \w, including underscores. Conveniently, most languages recognise identifiers containing letters, digits and underscores.
Quantifiers allow character classes to be repeated. The most common quantifiers are question mark, ?, asterisk, *, and plus, +. Zero or one repetition is ?. Zero or more repetitions is *. One or more repetitions is +.
use English;
$string = "Novice to Expert in a 3 day Perl course.\n";
if( $string =~ /\w+/ ) {
  # \w+ matches one or more alphanumeric characters in a row
  print "Matched: $MATCH\n";  # Matched: Novice
}
Readable English names for some Perl special variables are provided by the English Perl module.   $MATCH gets a copy of the substring successfully matched.   Without using the English Perl module $MATCH would have to be called $&.

use English;
$string = "Novice to Expert in a 3 day Perl course.\n";
if( $string =~ /Perl\s+\w+/ ) {
  #             ^^^^          matches Perl
  #                 ^^^       matches one or more white space characters
  #                                    (including space, tab and newline)
  #                    ^^^    matches one or more alphanumeric characters
  print "Matched: $MATCH\n";  # Matched: Perl course
}
#  \w?    Zero or one letter, digit or underscore
#  \w     One letter, digit or underscore
#  \w*    Zero or more letters, digits or underscores
#  \w+    One or more letters, digits or underscores
#  \W     One character but not a letter, digit or underscore

#  \s     White space character, space, tab or newline
#  \S     One character but not a space, tab or newline

Groups

Sub expressions can be grouped together and stored in back reference buffers. Round brackets are used to (group) sub expressions. The back reference buffers have the names $1, $2, $3 etc. The substring that matches the first bracketed group is copied into $1. The second into $2 etc.
There is a Xilinx Vital timing model in a file called chip_timesim.vhd. Here is one component instantiation from it:
c4_n001449 : X_LUT4
    generic map(
      INIT => X"0001"
    )
    port map (
      ADR0 => c4_count(4),
      ADR1 => c4_count(18),
      ADR2 => c4_count(3),
      ADR3 => c4_count(5),
      O => CHOICE121_pack_1
    );

The component name, X_LUT4, could be matched using a regular expression containing a group. This short script opens the file, finds every component instantiation reporting the component name.

open( VHDL_FILE, 'chip_timesim.vhd' );
while( $line = <VHDL_FILE> ) {
  if( $line =~ /\w+\s*:\s*(X_\w+)/ ) {
#               ^^^                      Instance label
#                  ^^^                   Zero or more white space characters
#                     ^                  :
#                      ^^^               Zero or more white space characters
#                          ^^^^^         Group containing a word beginning with X_
#                                                                 (copied into $1)
    print "Found instantiation of $1\n";
  }
}

Netlist Filtering

The following script takes the filename of a Xilinx netlist from the command line. It finds and counts every component instantiation. Finally, it prints a list of all the component names found and the number of appearances.

# Pulling it all together
# Everything in this script is described above

$netlist_filename = $ARGV[0];
open( VHDL_FILE, $netlist_filename );

while( $line = <VHDL_FILE> ) {
  if( $line =~ /\w+\s*:\s*(X_\w+)/ ) {
    $component_hash{$1}++;
  }
}

@name_array = keys %component_hash;
foreach $component_name ( @name_array ) {
  print "$component_name: $component_hash{$component_name}\n";
}
Extracting information from text files is easy given a little Perl knowledge. The following output was generated by the above script:
X_FF: 56
X_AND2: 29
X_ONE: 25
X_INV_PP: 23
X_BUF_PP: 395
X_ZERO: 4
X_TOC: 1
X_XOR2: 53
X_BUFGMUX: 1
X_OR2: 8
X_ROC: 1
X_MUX2: 96
X_LUT4: 123
X_TRI_PP: 20

Tuesday, September 6, 2011

Secret Perl Operators

The Spaceship Operator <=>

<=> is the spaceship operator. Most commonly it's used to sort a list of numbers. Here is an example:
my @numbers = (-59, 99, 87, 1900, 42, 1, -999, 30000, 0);
my @sorted = sort { $a <=> $b } @numbers;
print "@sorted\n";

# output: -999 -59 0 1 42 87 99 1900 30000
If you don't specify a block with the spaceship operator to sort() function, it will treat the numbers as strings and sort them asciibetically:
my @numbers = (-59, 99, 87, 1900, 42, 1, -999, 30000, 0);
my @sorted = sort @numbers;
print "@sorted\n";

# output: -59 -999 0 1 1900 30000 42 87 99
In general the spaceship operator is defined as following:
  • $a <=> $b is -1 if $a < $b.
  • $a <=> $b is 0 if $a == $b.
  • $a <=> $b is 1 if $a > $b.
  • $a <=> $b is undef if $a and $b are NaN.

The Eskimo Greeting Operator }{

The Eskimo greeting operator can be most frequently met in Perl one-liners.
For example, this one-liner uses the Eskimo greeting to emulate `wc -l` command and prints the number of lines in a file:
perl -lne '}{ print $.' file
Here the Eskimo greets the print function. To understand what happens here, you have to know what the -n command line option does. It causes Perl to assume the following loop around your program:
while (<>) {
  ...
}
Where `...` contains the code specified by the -e command line option. If the code specified is `}{ ...` then it causes the while loop to be closed with no actions to be done and only the `...` part gets executed.
Therefore the one-liner above is equivalent to:
while (<>) {
}
{
print $.
}
This just prints the special variable $. which is the number of input lines processed.
This can be extended further and we can have Eskimo greet code on both sides:
perl -lne 'code1 }{ code2'
Code1 gets executed within the loop and code2 after the loop is done:
while (<>) {
  code1
}
{
  code2
}
If you are interested in the topic of Perl one-liners, see the first part of my article "Perl One-Liners Explained".

The Goatse Operator =()=

The Goatse operator, as nasty as it may sound, doesn't do any nasty things. Instead it does a wonderful thing and causes an expression on the right to be evaluated in array context.
Here is an example,
my $str = "5 foo 6 bar 7 baz";
my $count =()= $str =~ /\d/g;
print $count;
This program prints 3 - the number of digits in $str. How does it do it? Let's deparse the 2nd line:
(my $count = (() = ($str =~ /\d/g)));
What happens here is that the expression ($str =~ /\d/g) gets assigned to the empty list (). Assigning to a list forces the list context. The whole (() = ($str =~ /\d/g)) thing gets evaluated in list context, but then it gets assigned to a scalar which causes it to get evaluated again in scalar context. So what we have is a list assignment in scalar context. The key thing to remember is that a list assignment in scalar context returns the number of elements on the right-hand side of the list assignment. In this example the right-hand side of the list assignment is ($str =~ /\d/g). This matches globally (/g flag) and finds 3 digits in $str. Therefore the result is 3.

The Turtle Operator "@{[]}"

I couldn't find the name of this operator therefore I decided to name it the turtle operator, because it looks a bit like a turtle, @ being the head, and {[]} being the shell.
This operator is useful for interpolating an array inside a string.
Compare these two examples:
print "these people @{[get_names()]} get promoted"
and
print "these people ", join " ",get_names(), " get promoted"
Clearly, the first example wins for code clarity.
More precisely, writing
print "@{[something]}"
is exactly the same as writing
print join $", something

The Inchworm Operator ~~

The inchworm operator can be used to force scalar context.
Here is an example with localtime() function. In scalar context localtime() returns human readable time, but in list context it returns a 9-tuple with various date elements.
$ perl -le 'print ~~localtime'
Mon Nov 30 09:06:13 2009
Here localtime was evaluated in scalar context, even though it was called within print that forces list context. It returned human readable date and time.
$ perl -le 'print localtime'
579301010913330
Here localtime returned a list of 9 elements and print function just printed them one after another. To really see that it's a list of 9 elements, let's use the turtle operator:
$ perl -le 'print "@{[localtime]}"'
5 13 9 30 10 109 1 333 0

The Inchworm-On-A-Stick Operator ~-

For numbers greater than 0, this operator decrements them by one. Example:
my $x = 5;
print ~-$x;

# prints 4
It works because ~-$x parses to (~(-$x)), which on a two-complement machine is effectively the same as $x-1.

The Spacestation Operator -+-

The spacestation operator turns a string starting with positive number into a number. Here are some examples:
print -+-"4zy"   # prints 4
print -+-'3.99'  # prints 3.99
print -+-'2e5'   # prints 200000

The Venus Operator 0+

It's named the Venus operator because the astronomical symbol for the planet Venus looks similar.
It does the same as the spacestation operator, it numifies a string, but it binds less tightly than spacestation. An example:
print 0+"4zy"  # prints 4

Saturday, August 20, 2011

Initialize (clear) an array

Initialize (clear) an array.

Solution

my @array = ();
 
 
Solution
$#array is the subscript of the last element of the array (which is one less than the length of the array, since arrays start from zero). Assigning to $#array changes the length of the array @array, hence you can destroy (or clear) all values of the array between the last element and the newly assigned position. By assigning -1, everything is destroyed and the array is cleared. I recommend the above solution to this one.

$#array = -1;

Thursday, August 4, 2011

How to shuffle the values in a hash?

use List::Util qw(shuffle);

%hash = (this => 0,
is => 1,
a => 2,
test => 3);

my @values = shuffle(values %hash);
map { $hash{$_} = shift(@values) } (keys %hash);

print "$_\t$hash{$_}\n" foreach keys %hash;

Perl : Numeric Range Pattern Matching (IP)

$ip=~/(\d+)\.(\d+)\.(\d+)\.(\
d+)/;
if ($1>=0 && $1<=255 && $2>=0 && $2<=255 && $3>=0 && $3<=255 && $4>=0
&& $4<=255)
{
}

OR


$ip=~/\b((2[0-5][0-5]\.)|(1?[0-9]?[0-9]\.)){3}((2[0-5][0-5])|(1?[0-9]?[0-9]))\b/

perl - Objects, Modules and Packages

Objects, Modules and Packages

Package basics

  • A package is a collection of methods
  • Lives in its own namespace
  • Package methods can be exported or called directly
    • Foo::bar()
    • Foo->bar()
    • bar() (if Foo exports it)

Module basics

  • A module is a file containing one or more packages
  • Most people use "module" and "package" interchangably

Object basics

  • An object is a blessed reference to a hash
    • It doesn't have to be a hash reference, but it's most common.
  • Blessing assigns a single class to an object
  • An object can be re-blessed
  • You can muck with the internals, but that doesn't mean you should

1;

  • Modules must end with a true value
  • It doesn't have to be 1
  • Packages don't have the same restriction

@ISA

Perl's object inheritance methods use @ISA to determine what classes a module inherits from. Years ago, inheritance was declared by modifying @ISA directly; now, most programs use the base pragma to declare inheritance.

The following are mostly equivalent:

    package Foo;
require Wango;
@ISA
= ( "Wango" );

package Foo;
use base "Wango";


source: http://perl101.org/objects.html

Perl References

References

References are scalars that refer to other variables

References are like pointers in C in that they refer to other variables. Create a reference with the \ operator.

    my $sref = \$scalar;
my $aref = \@array;
my $href = \%hash;
my $cref = \&subroutine;

The thing the reference point to is the "referent".

Dereference a reference with the appropriate sigil, preferably in squiggly braces.

    my $other_scalar = ${$sref};
my @other_array = @{$aref};
my %other_hash = %{$href};
&{$cref} # Call the referent.

Arrow pointer is easier way to dereference.

To access array and hashrefs, use the -> operator.

    my $stooge = $aref->[1];
my $stooge = $href->{Curly};

ref vs isa

  • A reference belongs to one class
  • You can check this class with ref
  • An object reference can inherit from other classes
  • You can ask an object if it inherited from a class with isa
  • Don't use ref without a good reason
  • isa is part of the UNIVERSAL package, so you can call it on objects
        my $mech = WWW::Mechanize->new;
    print "ok\n" if $mech->isa('LWP::UserAgent');

References to anonymous subroutines

Subroutines can be assigned to a variable, then called, allowing code references to be passed around and used at will. This can come in handy if, for example, you're writing a subroutine that needs to execute supplied code as part of its work.

    my $casefix = sub { return ucfirst lc $_[0] };

my $color = $casefix->("rED");
print "Color: $color\n"; # prints Red



source: http://perl101.org/references.html

Saturday, July 9, 2011

File::Base​name Module Example in perl

use File::Basename;

($name,$path,$suffix) = fileparse($fullname,@suffixlist);

$name = fileparse($fullname,@suffixlist);
$basename = basename($fullname,@suffixlist);
$dirname  = dirname($fullname);

various method of array size in perl -- array length

#----------------------------#
# create a simple Perl array #
#----------------------------#
@foods = qw(burgers fries shakes);

#-------------------------------------------------#
# three different ways to get the Perl array size #
#-------------------------------------------------#

# 1) perl array size with implicit scalar conversion:
$size1 = @foods;

# 2) perl array size with explicit scalar conversion:
$size2 = scalar @foods;

# 3) perl array size with using the index of the last
#    element in the array, plus one:
$size3 = $#foods + 1;

# print the array sizes
printf("The sizes are %d, %d, and %d\n", $size1, $size2, $size3);

Perl DBI examples for DBD::mysql

For more examples see perldoc DBI and perldoc DBD::mysql or online
versions available at e.g.
http://cpan.uwinnipeg.ca/htdocs/DBI/DBI.html.

Note: For clarity, the following examples contain basic Perl code
snippets which do not use my or other recommended practices. For happy
Perl programming always use the pragma

use strict;
use warnings;

at the start of your scripts.
Connecting to a database

use DBI;
$dbh = DBI->connect('DBI:mysql:databasename', 'username', 'password'
                  ) || die "Could not connect to database: $DBI::errstr";
# (insert query examples here...)
$dbh->disconnect();

Connecting to a different host:


$dbh = DBI->connect('DBI:mysql:databasename;host=db.example.com',
'username', 'password',
                   { RaiseError => 1 }
                  );

Simple query

$dbh->do('CREATE TABLE exmpl_tbl (id INT, val VARCHAR(100))');
$dbh->do('INSERT INTO exmpl_tbl VALUES(1, ?)', undef, 'Hello');
$dbh->do('INSERT INTO exmpl_tbl VALUES(2, ?)', undef, 'World');
$c = $dbh->do('DELETE FROM exmpl_tbl WHERE id=1');
print "Deleted $c rows\n";

(Do not use $dbh->do() for SELECT statements because it does not
return a statement handle, making it impossible to fetch data)
Typical query

$sth = $dbh->prepare('SELECT val FROM exmpl_tbl WHERE id=1');
$sth->execute();
$result = $sth->fetchrow_hashref();
print "Value returned: $result->{val}\n";

Query using placeholders

$sth = $dbh->prepare('SELECT id FROM exmpl_tbl WHERE val=?',
undef, 'World');
@result = $sth->fetchrow_array();
print "ID of World is $result[0]\n";

Execute and fetch in one command

$sth = $dbh->prepare('SELECT * FROM exmpl_tbl');
$results = $dbh->selectall_hashref('SELECT * FROM exmpl_tbl', 'id');
foreach my $id (keys %$results) {
 print "Value of ID $id is $results->{$id}->{val}\n";
}

Password Regular Expression in perl example

 Only contains alphanumeric and the following special characters: !@#$%^&*
   Contains at least 1 of the special characters in the list above
   The required special character can appear anywhere in the string
(for example: !abc, a!bc, abc!)


The regular expression you're looking for is:

/^(?=.*[\!\@\#\$\%\^\&\*])[A-Za-z0-9\!\@\#\$\%\^\&\*]+$/

which will guarantee the string contains one of your special
characters using (?=) positive lookahead.


OR

^(?=.*?[!@#$%\^&*])((?!_)[\w!@#$%\^&*])+$

It looks ensure the special character is found anywhere in the string.
Once it finds it, it matches the rest of the string as long as the
string consists of only word characters, digits, and the special
characters.

Edit: The negativelookahead prevents _ (underscore).


OR


Say you want minimum requirements of "at least one non-alphanumeric
character, at least 8 characters". Use two look-aheads:

^(?=.*[^a-zA-Z0-9])(?=.{8,}$)

Other than that - let users choose the passwords they like.

mysql AutoCommit in perl

my $dbh= DBI->connect(............  );

my $sth = $dbh->prepare("call sp_get_workitems (1,1)");
$dbh->begin_work  or die $dbh->errstr;       #$dbh->{'AutoCommit'} =
0; same as begin_work
$sth->execute();
my ($result)= $sth->fetchrow_array();

$dbh->commit;

perl file test syntax

It checks whether the directory exists or not. There are many more
file test operations available, such as below:

  1. -r File is readable by effective uid/gid.
  2. -w File is writable by effective uid/gid.
  3. -x File is executable by effective uid/gid.
  4. -o File is owned by effective uid.
  5. -R File is readable by real uid/gid.
  6. -W File is writable by real uid/gid.
  7. -X File is executable by real uid/gid.
  8. -O File is owned by real uid.
  9. -e File exists.
 10. -z File has zero size (is empty).
 11. -s File has nonzero size (returns size in bytes).
 12. -f File is a plain file.
 13. -d File is a directory.
 14. -l File is a symbolic link.
 15. -p File is a named pipe (FIFO), or Filehandle is a pipe.
 16. -S File is a socket.
 17. -b File is a block special file.
 18. -c File is a character special file.
 19. -t Filehandle is opened to a tty.
 20. -u File has setuid bit set.
 21. -g File has setgid bit set.
 22. -k File has sticky bit set.
 23. -T File is an ASCII text file (heuristic guess).
 24. -B File is a "binary" file (opposite of -T).
 25. -M Script start time minus file modification time, in days.
 26. -A Same for access time.
 27. -C Same for inode change time (Unix, may differ for other platforms)

How to create multi-dime​nsional array in perl?

You get a one-dimensional array because the array @a1 is expanded
inside the parens. So, assuming:

my @a1 = (1,2);
my @a2 = (@a1,3);

Then your second statement is equivalent to my @a2 = (1,2,3);.

When creating a multi-dimensional array, you have a few choices:

Direct assignment of each value
Dereferencing an existing array
Inserting a reference

The first option is basically $array[0][0] = 1; Not very exciting.

The second is doing this: my @a2 = (\@a1, 3); Note that this makes a
reference to the namespace for the array @a1, so if you later change
@a1, the values inside @a2 will also change. Not always a recommended
option.

A variation of the second option is doing this: my @a2 = ([1,2], 3);
The brackets will create an anonymous array, which has no namespace,
only a memory address, and will only exist inside @a2.

The third option, a bit more obscure, is doing this: my $a1 = [1,2];
my @a2 = ($a1, 3); It will do exactly the same thing as 2, only the
array reference is already in a scalar variable, called $a1.

Note the difference between () and [] when assigning to arrays.
Brackets [] create an anonymous array, which returns an array
reference as a scalar value (e.g. that can be held by $a1, or $a2[0]).

Parens on the other hand do nothing at all really, except change the
precedence of operators.

Consider this piece of code:

my @a2 = 1, 2, 3;
print "@a2";

This will print 1. If you use warnings, you will also get a warning
such as: Useless use of a constant in void context. What happens is
basically this:

my @a2 = 1;
2, 3;

Because commas (,) have a lower precedence than equalsign =. (See
"Operator Precedence and Associativity" in perldoc perlop)

What parens do is simply negate the default precedence of = and ,, and
group 1,2,3 together in a list, which is then passed to @a2.

So, in short, brackets [] have some magic in them: They create
anonymous arrays. Parens () just change precedence, much like in math.

There is much to read in the documentation. Someone here once showed
me a very good link for dereferencing, but I don't recall what it is.
In perldoc perlreftut you will find a basic tutorial on references.
And in perldoc perldsc you will find documentation on data structures
(thanks Oesor for reminding me).

What does this split expression mean in Perl?

while (<>) {
 chomp;
 print join("\t", (split /:/)[0, 2, 1, 5] ), "\n";
}

What does (split /:/)[0, 2, 1, 5] mean here?


It means

my @fields            = split /:/, $_;
my @fields_to_display = ($fields[0], $fields[2], $fields[1], $fields[5]);

create a list by splitting the line on :, then take elements 0,2,1,5
of this list

What's the difference between exists and defined

defined checks the value of the variable, exists checks if it has been
previously declared/initialized. If it exists, plain and simple.

E.g.:

$hash{$key} = undef;
# various return values:
exists  $hash{$key};  # true
defined $hash{$key};  # false
$hash{$key};          # false

$hash{$key} = 0;
# various return values:
exists  $hash{$key};  # true
defined $hash{$key};  # true
$hash{$key};          # false
exists $hash{$foo};   # false

In Perl,is there a way to do simple arithmetic inside quotes?

$i = 5;
print "{$i*10}";

Sometimes I may need to do things like above,but Perl doesn't
interpret it the way I want,and I can only do it with another
variable.Is there a trick?



I suggest you use "printf":

printf("%s",$i*10);

How to copy keys from hash to array without duplicates​?

#Method 1:

You could make use of List::MoreUtils's uniq function:

use List::MoreUtils qw( uniq );

@a = uniq @a, keys %h;


#Method 2:
Convert the values you want into hash keys, then extract them

my %foo = map { $_ => 1  } @a, keys %h;
print sort keys %foo;


Method 3:
If you have Perl 5.10 and later, you can use smart matching (~~):

for my $key (keys %h) {
   push @a, $key unless $key ~~ @a;
}

Friday, June 10, 2011

Array to hash array example

use strict;
use warnings;

# for debugging
use Data::Dumper;

my @array = (
'ab cd ef',
'mn de fg',
);

my %hash;

for my $element (@array) {

if ($element =~ m{
^ # match the beginning of the
row
( \w{2} ) # match two characters
[ ] # match one space
(.*) # match the rest of the row
}mxs
) {
$hash{$1} = $2;
} else {
warn "error: incorrectly formatted array element: $element";
}

}

print Dumper \%hash;


OR


my %hash = map { split / ^ \S+ \K [ ]+ /x, $_ } @a;

See \K in perlre (5.10 or greater)

How can I skip lines when slurping a file in Perl

The basic idea of inserting, changing, or deleting a line from a text
file involves reading and printing the file to the point you want to
make the change, making the change, then reading and printing the rest
of the file. Perl doesn't provide random access to lines (especially
since the record input separator, $/, is mutable), although modules
such as Tie::File can fake it.

A Perl program to do these tasks takes the basic form of opening a
file, printing its lines, then closing the file:

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

while( <$in> )
       {
       print $out $_;
       }

   close $out;

Within that basic form, add the parts that you need to insert, change,
or delete lines.

To prepend lines to the beginning, print those lines before you enter
the loop that prints the existing lines.

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC

while( <$in> )
       {
       print $out $_;
       }

   close $out;

To change existing lines, insert the code to modify the lines inside
the while loop. In this case, the code finds all lowercased versions
of "perl" and uppercases them. The happens for every line, so be sure
that you're supposed to do that on every line!

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

print $out "# Add this line to the top\n";

while( <$in> )
       {
       s/\b(perl)\b/Perl/g;
       print $out $_;
       }

   close $out;

To change only a particular line, the input line number, $., is
useful. First read and print the lines up to the one you want to
change. Next, read the single line you want to change, change it, and
print it. After that, read the rest of the lines and print those:

while( <$in> )   # print the lines before the change
       {
       print $out $_;
       last if $. == 4; # line number before change
       }

my $line = <$in>;
$line =~ s/\b(perl)\b/Perl/g;
print $out $line;

while( <$in> )   # print the rest of the lines
       {
       print $out $_;
       }

To skip lines, use the looping controls. The next in this example
skips comment lines, and the last stops all processing once it
encounters either END or DATA.

while( <$in> )
       {
       next if /^\s+#/;             # skip comment lines
       last if /^__(END|DATA)__$/;  # stop at end of code marker
       print $out $_;
       }

Do the same sort of thing to delete a particular line by using next to
skip the lines you don't want to show up in the output. This example
skips every fifth line:

while( <$in> )
       {
       next unless $. % 5;
       print $out $_;
       }

If, for some odd reason, you really want to see the whole file at once
rather than processing line by line, you can slurp it in (as long as
you can fit the whole thing in memory!):

open my $in,  '<',  $file      or die "Can't read old file: $!"
open my $out, '>', "$file.new" or die "Can't write new file: $!";

my @lines = do { local $/; <$in> }; # slurp!

       # do your magic here

print $out @lines;

Modules such as File::Slurp and Tie::File can help with that too. If
you can, however, avoid reading the entire file at once. Perl won't
give that memory back to the operating system until the process
finishes.

You can also use Perl one-liners to modify a file in-place. The
following changes all 'Fred' to 'Barney' in inFile.txt, overwriting
the file with the new contents. With the -p switch, Perl wraps a while
loop around the code you specify with -e, and -i turns on in-place
editing. The current line is in $. With -p, Perl automatically prints
the value of $ at the end of the loop. See perlrun for more details.

perl -pi -e 's/Fred/Barney/' inFile.txt

To make a backup of inFile.txt, give -i a file extension to add:

perl -pi.bak -e 's/Fred/Barney/' inFile.txt

To change only the fifth line, you can add a test checking $., the
input line number, then only perform the operation when the test
passes:

perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt

To add lines before a certain line, you can add a line (or lines!)
before Perl prints $_:

perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt

You can even add a line to the beginning of a file, since the current
line prints at the end of the loop:

perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt

To insert a line after one already in the file, use the -n switch.
It's just like -p except that it doesn't print $_ at the end of the
loop, so you have to do that yourself. In this case, print $_ first,
then print the line that you want to add.

perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt

To delete lines, only print the ones that you want.

perl -ni -e 'print unless /d/' inFile.txt

       ... or ...

perl -pi -e 'next unless /d/' inFile.txt

File::Basename in perl Example

use File::Basename;

($name,$path,$suffix) = fileparse($fullname,@
suffixlist);

$name = fileparse($fullname,@suffixlist);
$basename = basename($fullname,@suffixlist);
$dirname  = dirname($fullname);

Perl Intervew Question


What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?
5
length() is a built-in prototyped as sub length($), and a scalar prototype silently changes aggregates into radically different forms. The scalar sense of a hash is false (0) if it's empty, otherwise it's a string representing the fullness of the buckets, like "18/32" or "39/64". The length of that string is likely to be 5. Likewise, `length(@a)' would be 2 if there were 37 elements in @a.

If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{"Foo::".EXPR}?
The second is disallowed under `use strict "refs"'.
Dereferencing a string with *{"STR"} is disallowed under the refs stricture, although *{STR} would not be. This is similar in spirit to the way ${"STR"} is always the symbol table variable, while ${STR} may be the lexical variable. If it's not a bareword, you're playing with the symbol table in a particular dynamic fashion.
How do I do < fill-in-the-blank > for each element in an array?
#!/usr/bin/perl -w
@homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth');
foreach (@homeRunHitters) {
print "$_ hit a lot of home runs in one year\n";
}

How do I replace every <TAB> character in a file with a comma?
perl -pi.bak -e 's/\t/,/g' myfile.txt
What is the easiest way to download the contents of a URL with Perl?
Once you have the libwww-perl library, LWP.pm installed, the code is this:
#!/usr/bin/perl
use LWP::Simple;
$url = get 'http://www.websitename.com/';

How to concatenate strings with Perl?
Method #1 - using Perl's dot operator:
$name = 'checkbook';
$filename = "/tmp/" . $name . ".tmp";

Method #2 - using Perl's join function
$name = "checkbook";
$filename = join "", "/tmp/", $name, ".tmp";

Method #3 - usual way of concatenating strings
$filename = "/tmp/${name}.tmp";

How do I read command-line arguments with Perl?
With Perl, command-line arguments are stored in the array named @ARGV.
$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.
Here's a simple program:
#!/usr/bin/perl
$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";
foreach $argnum (0 .. $#ARGV) {
print "$ARGV[$argnum]\n";
}
When would `local $_' in a function ruin your day?
When your caller was in the middle for a while(m//g) loop
The /g state on a global variable is not protected by running local on it. That'll teach you to stop using locals. Too bad $_ can't be the target of a my() -- yet.

What happens to objects lost in "unreachable" memory..... ?
What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }' ?

Their destructors are called when that interpreter thread shuts down.
When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code.

Assume that $ref refers to a scalar, an array, a hash or to some nested data structure. Explain the following statements:
$$ref; # returns a scalar
$$ref[0]; # returns the first element of that array
$ref- > [0]; # returns the first element of that array
@$ref; # returns the contents of that array, or number of elements, in scalar context
$&$ref; # returns the last index in that array
$ref- > [0][5]; # returns the sixth element in the first row
@{$ref- > {key}} # returns the contents of the array that

How do you match one letter in the current locale?
/[^\W_\d]/
We don't have full POSIX regexps, so you can't get at the isalpha() <ctype.h> macro save indirectly. You ask for one byte which is neither a non-alphanumunder, nor an under, nor a numeric. That leaves just the alphas, which is what you want.
Perl uses single or double quotes to surround a zero or more characters. Are the single(' ') or double quotes (" ") identical?
They are not identical. There are several differences between using single quotes and double quotes for strings.
1. The double-quoted string will perform variable interpolation on its contents. That is, any variable references inside the quotes will be replaced by the actual values.
2. The single-quoted string will print just like it is. It doesn't care the dollar signs.
3. The double-quoted string can contain the escape characters like newline, tab, carraige return, etc.
4. The single-quoted string can contain the escape sequences, like single quote, backward slash, etc.
How many ways can we express string in Perl?
Many. For example 'this is a string' can be expressed in:
"this is a string"
qq/this is a string like double-quoted string/
qq^this is a string like double-quoted string^
q/this is a string/
q&this is a string&
q(this is a string)
How do you give functions private variables that retain their values between calls?
Create a scope surrounding that sub that contains lexicals.
Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus:
{ my $i = 0; sub next_i { $i++ } sub last_i { --$i } }
creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.
What is meant by die in a perl program?
Don’t proceed with the rest of the script of the pervious defined condition is NOT met.
What is the use of require and what does it
require is a call to an external program/condition, that has to be met before the scrcipt/program can continue.
What does this mean ‘$^0′
$^ - Holds the name of the default heading format for the default file handle. Normally, it is equal to the file handle’s name with _TOP appended to it.
What is meant by ‘chomp’?
chomp is used to eliminate the new line character. It can used in many different scenarios.
For ex: excuteScript.pl firstArgument.
$firstArg = $ARGV[0];
chomp $firstArg; –> to get rid of the carrige return.
What is meant by a ‘pack’ in perl?
Pack converts a list into a binary representation
Takes an array or list of values and packs it into a binary structure, returning the string containing the structure
What does this symbol mean ‘->’
In Perl it is an infix dereference operator. The if the rhs is an array subscript, or a hash key, or a subroutine, then the lhs must be a reference, can also be used as method invocation: invocant->method
reference the method of a module.
What are the benefits of having global and local variables?
Global variables can be called upon any where in the script. Local variables are not valid outside the code blocks they are created in.
What is a subroutine?
A subroutine is like a function … called upon to execute a task.
What does the word ‘&my variable’ mean? What does the symbol ‘&’ means? What’s purpose of it?
&myvariable is calling a sub-routine. & is used to identify a sub-routine.
What does $_ means?
Default variable in PERL
What interface used in PERL to connect to database. How do you connect to database in perl
DBI.There is DBI module.use DBI;my $dbh = DBI->connect(’dbi:Oracle:orcl’, ‘username’, ‘password’,)
When do you not use PERL for a project?
There’s a lot of text processing
Web-based applications
Fast/expidient development
Shell scripts grow into libraries
Heavy Data manipulation (auditing, accounting, checking etc… backend processing)
Data extraction
transform loading (database etc.)
System admin etc…
Name an instance you used in CPAN module
CGI, DBI are very common packages used from CPAN.
Difference between for & foreach,exec & system?
There is no difference between for and foreach. exec runs the given process, switches to its name and never returns while system forks off the given process, waits for it to complete and then returns.
What’s the purpose of -w.strict,-T?
-w option enables warning.use strict pragma is used then you should declare variables before there use.
What is the use of “STDERR()”?
How to Connect with SqlServer from perl and how to display database table info?
There is a module in perl named DBI - Database independent interface which will be used to connect to any database by using same code. Along with DBI we should use database specific module here it is SQL server. for MSaccess it is DBD::ODBC, for MySQL it is DBD::mysql driver, for integrating oracle with perl use DBD::oracle driver is used. IIy for SQL server there are avilabale many custom defined ppm( perl package manager) like Win32::ODBC, mssql::oleDB etc.so, together with DBI, mssql::oleDB we can access SQL server database from perl. the commands to access database is same for any database.
What’s the significance of @ISA, @EXPORT @EXPORT_OK %EXPORT_TAGS list & hashes in a perl package?
@ISA -> each package has its own @ISA array. this array keep track of classes it is inheriting.
package child;
@ISA=( parentclass);
@EXPORT this array stores the subroutins to be exported from a module.
@EXPORT_OK this array stores the subroutins to be exported only on request.
What is difference between “Use” and “require”. In which case should “Use” be used and not “Require”?
Use :
1. The method is used only for the modules(only to include .pm type file)
2. The included objects are varified at the time of compilation.
3. No Need to give file extension.
Require:
1. The method is used for both libraries and modules.
2. The included objects are varified at the run time.
3. Need to give file Extension.
What is the difference between “my” and “local” variable scope declarations. ?
The variables declared with my() are visible only within the scope of the block which names them. They are not visible outside of this block, not even in routines or blocks that it calls. local() variables, on the other hand, are visible to routines that are called from the block where they are declared. Neither is visible after the end (the final closing curly brace) of the block at all.
What is a static function?
A static function is a function whose scope is limited to the current source file. Scope refers to the visibility of a function or variable. If the function or variable is visible outside of the current source file, it is said tohave global, or external, scope. If the function or variable is not visible outside of the current source file, itis said to have local, or static, scope.
also if a variable is declared to be static, then its value doesn’t change within that function.
How do I find which modules are installed on my system?

You can use the ExtUtils::Installed module to show all installed distributions, although it can take awhile to do its magic. The standard library which comes with Perl just shows up as "Perl" (although you can get those with Module::CoreList).

use ExtUtils::Installed;

my $inst = ExtUtils::Installed->new();
my @modules = $inst->modules();

If you want a list of all of the Perl module filenames, you can use File::Find::Rule.

use File::Find::Rule;

my @files = File::Find::Rule->file()->name( '*.pm' )->in( @INC );

If you do not have that module, you can do the same thing with File::Find which is part of the standard library.

use File::Find;
my @files;

find(
sub {
push @files, $File::Find::name
if -f $File::Find::name && /\.pm$/
},

@INC
);

print join "\n", @files;

If you simply need to quickly check to see if a module is available, you can check for its documentation. If you can read the documentation the module is most likely installed. If you cannot read the documentation, the module might not have any (in rare cases).

prompt% perldoc Module::Name

You can also try to include the module in a one-liner to see if perl finds it.

perl -MModule::Name -e1

How can I compare two dates and find the difference?
You could just store all your dates as a number and then subtract. Life isn't always that simple though. If you want to work with formatted dates, the Date::Manip, Date::Calc, or DateTime modules can help you.
How do I remove consecutive pairs of characters?
You can use the substitution operator to find pairs of characters (or runs of characters) and replace them with a single instance. In this substitution, we find a character in (.). The memory parentheses store the matched character in the back-reference \1 and we use that to require that the same thing immediately follow it. We replace that part of the string with the character in $1.

s/(.)\1/$1/g;

We can also use the transliteration operator, tr///. In this example, the search list side of our tr/// contains nothing, but the c option complements that so it contains everything. The replacement list also contains nothing, so the transliteration is almost a no-op since it won't do any replacements (or more exactly, replace the character with itself). However, the s option squashes duplicated and consecutive characters in the string so a character does not show up next to itself

my $str = 'Haarlem'; # in the Netherlands
$str =~ tr///cs; # Now Harlem, like in New York


How can I access or change N characters of a string?


You can access the first characters of a string with substr(). To get the first character, for example, start at position 0 and grab the string of length 1.

$string = "Just another Perl Hacker";
$first_char = substr( $string, 0, 1 ); # 'J'

To change part of a string, you can use the optional fourth argument which is the replacement string.

substr( $string, 13, 4, "Perl 5.8.0" );

You can also use substr() as an lvalue.

substr( $string, 13, 4 ) = "Perl 5.8.0";


How do I change the Nth occurrence of something?

You have to keep track of N yourself. For example, let's say you want to change the fifth occurrence of "whoever" or "whomever" into "whosoever" or "whomsoever", case insensitively. These all assume that $_ contains the string to be altered.

$count = 0;
s{((whom?)ever)}{
++$count == 5 # is it the 5th?
? "${2}soever" # yes, swap
: $1 # renege and leave it there
}ige;

In the more general case, you can use the /g modifier in a while loop, keeping count of matches.

$WANT = 3;
$count = 0;
$_ = "One fish two fish red fish blue fish";
while (/(\w+)\s+fish\b/gi) {
if (++$count == $WANT) {
print "The third fish is a $1 one.\n";
}
}

That prints out: "The third fish is a red one." You can also use a repetition count and repeated pattern like this:

/(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;


How can I count the number of occurrences of a substring within a string?

There are a number of ways, with varying efficiency. If you want a count of a certain single character (X) within a string, you can use the tr/// function like so:

$string = "ThisXlineXhasXsomeXx'sXinXit";
$count = ($string =~ tr/X//);
print "There are $count X characters in the string";

This is fine if you are just looking for a single character. However, if you are trying to count multiple character substrings within a larger string, tr/// won't work. What you can do is wrap a while() loop around a global pattern match. For example, let's count negative integers:

$string = "-9 55 48 -2 23 -76 4 14 -44";
while ($string =~ /-\d+/g) { $count++ }
print "There are $count negative numbers in the string";

Another version uses a global match in list context, then assigns the result to a scalar, producing a count of the number of matches.

$count = () = $string =~ /-\d+/g;


How do I capitalize all the words on one line?

To make the first letter of each word upper case:

$line =~ s/\b(\w)/\U$1/g;

This has the strange effect of turning "don't do it" into "Don'T Do It". Sometimes you might want this. Other times you might need a more thorough solution (Suggested by brian d foy):

$string =~ s/ (
(^\w) #at the beginning of the line
| # or
(\s\w) #preceded by whitespace
)
/\U$1/xg;

$string =~ s/([\w']+)/\u\L$1/g;

To make the whole line upper case:

$line = uc($line);

To force each word to be lower case, with the first letter upper case:

$line =~ s/(\w+)/\u\L$1/g;


What is the difference between a list and an array?

An array has a changeable length. A list does not. An array is something you can push or pop, while a list is a set of values. Some people make the distinction that a list is a value while an array is a variable. Subroutines are passed and return lists, you put things into list context, you initialize arrays with lists, and you foreach() across a list. @ variables are arrays, anonymous arrays are arrays, arrays in scalar context behave like the number of elements in them, subroutines access their arguments through the array @_, and push/pop/shift only work on arrays.

As a side note, there's no such thing as a list in scalar context. When you say

$scalar = (2, 5, 7, 9);

you're using the comma operator in scalar context, so it uses the scalar comma operator. There never was a list there at all! This causes the last value to be returned: 9.


Why does defined() return true on empty arrays and hashes?

The short story is that you should probably only use defined on scalars or functions, not on aggregates (arrays and hashes).


How do I sort a hash (optionally by value instead of key)?

To sort a hash, start with the keys. In this example, we give the list of keys to the sort function which then compares them ASCIIbetically (which might be affected by your locale settings). The output list has the keys in ASCIIbetical order. Once we have the keys, we can go through them to create a report which lists the keys in ASCIIbetical order.

my @keys = sort { $a cmp $b } keys %hash;

foreach my $key ( @keys )
{
printf "%-20s %6d\n", $key, $hash{$value};
}

We could get more fancy in the sort() block though. Instead of comparing the keys, we can compute a value with them and use that value as the comparison.

For instance, to make our report order case-insensitive, we use the \L sequence in a double-quoted string to make everything lowercase. The sort() block then compares the lowercased values to determine in which order to put the keys.

my @keys = sort { "\L$a" cmp "\L$b" } keys %hash;

Note: if the computation is expensive or the hash has many elements, you may want to look at the Schwartzian Transform to cache the computation results.

If we want to sort by the hash value instead, we use the hash key to look it up. We still get out a list of keys, but this time they are ordered by their value.

my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;

From there we can get more complex. If the hash values are the same, we can provide a secondary sort on the hash key.

my @keys = sort {
$hash{$a} <=> $hash{$b}
or
"\L$a" cmp "\L$b"
} keys %hash;


How can I make my hash remember the order I put elements into it?

Use the Tie::IxHash from CPAN.

use Tie::IxHash;

tie my %myhash, 'Tie::IxHash';

for (my $i=0; $i<20; $i++) {
$myhash{$i} = 2*$i;
}

my @keys = keys %myhash;
# @keys = (0,1,2,3,...)


What's the difference between "delete" and "undef" with hashes?

Hashes contain pairs of scalars: the first is the key, the second is the value. The key will be coerced to a string, although the value can be any kind of scalar: string, number, or reference. If a key $key is present in %hash, exists($hash{$key}) will return true. The value for a given key can be undef, in which case $hash{$key} will be undef while exists $hash{$key} will return true. This corresponds to ($key, undef) being in the hash.

Pictures help... here's the %hash table:

keys values
+------+------+
| a | 3 |
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+

And these conditions hold

$hash{'a'} is true
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is true
exists $hash{'a'} is true (Perl 5 only)
grep ($_ eq 'a', keys %hash) is true

If you now say

undef $hash{'a'}

your table now reads:

keys values
+------+------+
| a | undef|
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+

and these conditions now hold; changes in caps:

$hash{'a'} is FALSE
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is FALSE
exists $hash{'a'} is true (Perl 5 only)
grep ($_ eq 'a', keys %hash) is true

Notice the last two: you have an undef value, but a defined key!

Now, consider this:

delete $hash{'a'}

your table now reads:

keys values
+------+------+
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+

and these conditions now hold; changes in caps:

$hash{'a'} is false
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is false
exists $hash{'a'} is FALSE (Perl 5 only)
grep ($_ eq 'a', keys %hash) is FALSE

See, the whole entry is gone!

How do I send e-mail from a Perl/CGI program on a Unix system?
Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We'll go through a quick example here.
Assuming that you've already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and send the e-mail message:
# the rest of your program is up here ...
open(MAIL, "|/usr/lib/sendmail -t");
print MAIL "To: $sendToAddress\n";
print MAIL "From: $myEmailAddress\n";
print MAIL "Subject: $subject\n";
print MAIL "This is the message body.\n";
print MAIL "Put your message here in the body.\n";
close (MAIL);
How to read from a pipeline with Perl
Example 1:
 
 To run the date command from a Perl program, and read the output
 of the command, all you need are a few lines of code like this:
 
    open(DATE, "date|");
    $theDate = <DATE>;
    close(DATE);
 
 The open() function runs the external date command, then opens
 a file handle DATE to the output of the date command.
 
 Next, the output of the date command is read into
 the variable $theDate through the file handle DATE.
  
 Example 2:
 
 The following code runs the "ps -f" command, and reads the output:
 
    open(PS_F, "ps -f|");
    while (<PS_F>) {
       ($uid,$pid,$ppid,$restOfLine) = split;
       # do whatever I want with the variables here ...
    }
    close(PS_F);
 

Why is it hard to call this function: sub y { "because" }
Because y is a kind of quoting operator.
The y/// operator is the sed-savvy synonym for tr///. That means y(3) would be like tr(), which would be looking for a second string, as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][A-Z].
 
 What does `$result = f() .. g()' really return?    
False so long as f() returns false, after which it returns true until g() returns true, and then starts the cycle again.
This is scalar not list context, so we have the bistable flip-flop range operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()'. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will both be evaluated on the same record. If you don't want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this:
$bingo = ( a() .. b() ) ... ( c() .. d() );
Why does Perl not have overloaded functions?
Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they're references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can't do this, you simply must resort to overloading of functions.

What does read() return at end of file?
0
A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().
What does `new $cur->{LINK}' do? (Assume the current package has no new() function of its own.)
$cur->new()->{LINK}
The indirect object syntax only has a single token lookahead. That means if new() is a method, it only grabs the very next token, not the entire following expression.
This is why `new $obj[23] arg' does't work, as well as why `print $fh[23] "stuff\n"' does't work. Mixing notations between the OO and IO notations is perilous. If you always use arrow syntax for method calls, and nothing else, you'll not be surprised.

How do I sort a hash by the hash value?
Here's a program that prints the contents
 of the grades hash, sorted numerically by the hash value:
 
 #!/usr/bin/perl -w
 
 # Help sort a hash by the hash 'value', not the 'key'.    
              to highest).
 sub hashValueAscendingNum {
    $grades{$a} <=> $grades{$b};
 }
 
 
 
 # Help sort a hash by the hash 'value', not the 'key'.    
 # Values are returned in descending numeric order         
 # (highest to lowest).
 sub hashValueDescendingNum {
    $grades{$b} <=> $grades{$a};
 }
 
 
 %grades = (
        student1 => 90,
        student2 => 75,
        student3 => 96,
        student4 => 55,
        student5 => 76,
 );
 
 print "\n\tGRADES IN ASCENDING NUMERIC ORDER:\n";
 foreach $key (sort hashValueAscendingNum (keys(%grades))) {
    print "\t\t$grades{$key} \t\t $key\n";
 }
 
 print "\n\tGRADES IN DESCENDING NUMERIC ORDER:\n";
 foreach $key (sort hashValueDescendingNum (keys(%grades))) {
    print "\t\t$grades{$key} \t\t $key\n";
 }
 


How to read file into hash array ?
 
 open(IN, "<name_file")
   or die "Couldn't open file for processing: $!";
 while (<IN>) {
   chomp;
   $hash_table{$_} = 0;
 }
 close IN;
 

How do you find the length of an array?
$@array

What value is returned by a lone `return;' statement?
The undefined value in scalar context, and the empty list value () in list context.
This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.

What's the difference between /^Foo/s and /^Foo/?
The second would match Foo other than at the start of the record if $* were set.
The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only at the ends of the string and not at ends of line as well -- just as they would if $* weren't set at all.
Does Perl have reference type?
Yes. Perl can make a scalar or hash type reference by using backslash operator.
For example
$str = "here we go"; # a scalar variable
$strref = \$str; # a reference to a scalar

@array = (1..10); # an array
$arrayref = \@array; # a reference to an array
Note that the reference itself is a scalar.


 print "$_ = $hash_table{$_}\n" foreach keys %hash_table;

How to dereference a reference?
There are a number of ways to dereference a reference.
Using two dollar signs to dereference a scalar.
$original = $$strref;
Using @ sign to dereference an array.
@list = @$arrayref;
Similar for hashes.
How do I generate a list of all .html files in a directory?
Here's a snippet of code that just prints a listing of every file in the current directory that ends with the extension .html:
#!/usr/bin/perl -w
opendir(DIR, ".");
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);
foreach $file (@files) {
print "$file\n";
}

What is Perl one-liner?
There are two ways a Perl script can be run:
--from a command line, called one-liner, that means you type and execute immediately on the command line. You'll need the -e option to start like "C:\ %gt perl -e "print \"Hello\";". One-liner doesn't mean one Perl statement. One-liner may contain many statements in one line.
--from a script file, called Perl program.

Assuming both a local($var) and a my($var) exist, what's the difference between ${var} and ${"var"}?
${var} is the lexical variable $var, and ${"var"} is the dynamic variable $var.
Note that because the second is a symbol table lookup, it is disallowed under `use strict "refs"'. The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), are variously knows as private, lexical, or scoped variable.
What happens when you return a reference to a private variable?
Perl keeps track of your variables, whether dynamic or otherwise, and doesn't free things before you're done using them.

How to turn on Perl warnings? Why is that important?
Perl is very forgiving of strange and sometimes wrong code, which can mean hours spent searching for bugs and weird results. Turning on warnings helps uncover common mistakes and strange places and save a lot of debugging time in the long run. There are various ways of turning on Perl warnings:
  • For Perl one-liner, use -w option on the command line.
  • On Unix or Windows, use the -w option in the shebang line (The first # line in the script). Note: Windows Perl interpreter may not require it.
  • For other systems, choose compiler warnings, or check compiler documentation.

What are scalar data and scalar variables?
Perl has a flexible concept of data types. Scalar means a single thing, like a number or string. So the Java concept of int, float, double and string equals to Perl\'s scalar in concept and the numbers and strings are exchangeable. Scalar variable is a Perl variable that is used to store scalar data. It uses a dollar sign $ and followed by one or more aphanumeric characters or underscores. It is case sensitive.

Why should I use the -w argument with my Perl programs?
Many Perl developers use the -w option of the interpreter, especially during the development stages of an application. This warning option turns on many warning messages that can help you understand and debug your applications.
To use this option on Unix systems, just include it on the first line of the program, like this:
#!/usr/bin/perl -w
If you develop Perl apps on a DOS/Windows computer, and you're creating a program named myApp.pl, you can turn on the warning messages when you run your program like this:
perl -w myApp.pl

Assuming $_ contains HTML, which of the following substitutions will remove all tags in it?
1.s/<.*>//g;
2.s/<.*?>//gs;
3.s/<\/?[A-Z]\w*(?:\s+[A-Z]\w*(?:\s*=\s*(?:(["']).*?\1|[\w-.]+))?)*\s*>//gsix;
You can't do that.
If it weren't for HTML comments, improperly formatted HTML, and tags with interesting data like < SCRIPT >, you could do this. Alas, you cannot. It takes a lot more smarts, and quite frankly, a real parser.

I want users send data by formmail but when they send nothing or call it from web site they will see error.
codes in PHP like this:
if (isset($HTTP_POST_VARS)){
..........
}
else{
echo ("error lalalalal")
}
How it will look in perl?
In php it will be like
if (isset($HTTP_POST_VARS)){
....
}
In perl, tried this.
if ($ENV{'REQUEST_METHOD'} eq 'POST'){
.....
}

What is the output of the following Perl program?
1 $p1 = "prog1.java";
2 $p1 =~ s/(.*)\.java/$1.cpp/;
3 print "$p1\n";
prog1.cpp

Why aren't Perl's patterns regular expressions?
Because Perl patterns have backreferences.
A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term.
What does Perl do if you try to exploit the execve(2) race involving setuid scripts?
Sends mail to root and exits.
It has been said that all programs advance to the point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it.
How do I do < fill-in-the-blank > for each element in a hash?
Here's a simple technique to process each element in a hash:
 
 #!/usr/bin/perl -w
 
 %days = (
         'Sun' =>'Sunday',
         'Mon' => 'Monday',
         'Tue' => 'Tuesday',
         'Wed' => 'Wednesday',
         'Thu' => 'Thursday',
         'Fri' => 'Friday',
         'Sat' => 'Saturday' );
 
 foreach $key (sort keys %days) {
   print "The long name for $key is $days{$key}.\n";
 

How do I sort a hash by the hash key?
Suppose we have a class of five students.
 Their names are kim, al, rocky, chrisy, and jane.
 
 Here's a test program that prints the contents
 of the grades hash, sorted by student name:
 
 #!/usr/bin/perl -w
 
 %grades = (
        kim       => 96,
        al        => 63,
        rocky     => 87,
        chrisy    => 96,
        jane      => 79,
 );
 
 print "\n\tGRADES SORTED BY STUDENT NAME:\n";
 foreach $key (sort (keys(%grades))) {
    print "\t\t$key \t\t$grades{$key}\n";
 }
 
 
 The output of this program looks like this:
 
 
        GRADES SORTED BY STUDENT NAME:
               al             63
               chrisy         96
               jane           79
               kim            96
               rocky          87
 
 
 
 }
 
}
 

How do you print out the next line from a filehandle with all its bytes reversed?
print scalar reverse scalar <FH>
Surprisingly enough, you have to put both the reverse and the <FH> into scalar context separately for this to work.
Why do you use Perl?
  • Perl is a powerful free interpreter.
  • Perl is portable, flexible and easy to learn.

How do I set environment variables in Perl programs?
you can just do something like this:
$ENV{'PATH'} = '...';
As you may remember, "%ENV" is a special hash in Perl that contains the value of all your environment variables.
Because %ENV is a hash, you can set environment variables just as you'd set the value of any Perl hash variable. Here's how you can set your PATH variable to make sure the following four directories are in your path::

$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/home/yourname/bin';
Which of these is a difference between C++ and Perl?
Perl can have objects whose data cannot be accessed outside its class, but C++ cannot.
Perl can use closures with unreachable private data as objects, and C++ doesn't support closures. Furthermore, C++ does support pointer arithmetic via `int *ip = (int*)&object', allowing you do look all over the object. Perl doesn't have pointer arithmetic. It also doesn't allow `#define private public' to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe.

How to open and read data files with Perl
Data files are opened in Perl using the open() function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from.
As an example, suppose you need to read some data from a file named "checkbook.txt". Here's a simple open statement that opens the checkbook file for read access: open (CHECKBOOK, "checkbook.txt"); In this example, the name "CHECKBOOK" is the file handle that you'll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named "CHECKBOOK".
Now that we've opened the checkbook file, we'd like to be able to read what's in it. Here's how to read one line of data from the checkbook file:
$record = < CHECKBOOK > ;
After this statement is executed, the variable $record contains the contents of the first line of the checkbook file. The "<>" symbol is called the line reading operator.
To print every record of information from the checkbook file

open (CHECKBOOK, "checkbook.txt") || die "couldn't open the file!";
while ($record = < CHECKBOOK >) {
print $record;
}
close(CHECKBOOK);

How do I do fill_in_the_blank for each file in a directory?
Here's code that just prints a listing of every file in the current directory:
#!/usr/bin/perl -w
opendir(DIR, ".");
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files) {
print "$file\n";
}
Perl is a high-level programming language with an eclectic heritage written by Larry Wall and a cast of thousands. It derives from the ubiquitous C programming language and to a lesser extent from sed, awk, the Unix shell, and at least a dozen other tools and languages. Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving quick prototyping, system utilities, software tools, system management tasks, database access, graphical programming, networking, and world wide web programming. These strengths make it especially popular with system administrators and CGI script authors, but mathematicians, geneticists, journalists, and even managers also use Perl. Maybe you should, too.

Purpose of first line #!usr/bin/perl in a Perl Program

When you run a program from your command line, you have certain information that is passed to the shell without you thinking about it. For example, you have a path, which tells the shell where it can look for files that you reference.

When a program runs through the web server as a CGI program, it does not have that path. Any programs that you invoke in your CGI program (like 'sendmail', for example) will need to be specified by a full path, so that the shell can find them when it attempts to execute your CGI program.

A common manifestation of this is the path to the script interpreter (often perl) indicated in the first line of your CGI program, which will look something like: #!/usr/bin/perl