Perl

From Wiki

Jump to: navigation, search

Contents

Perl

interactive Perl Shell: perl -de0


perl -MCPAN -e shell

To find a particular module, use the i command, followed by an expression that you want to search for:

       cpan> i /Time/

CPAN.pm will go out to the CPAN mirrror that you selected, download the list of modules, and tell you which ones match the search word.

To install a module, just type:

       cpan> install Time::CTime

Try/Catch

{{{

      1. begin_: try-catch block
   print "begin \n";
   eval{
       ### try block
       print Non_Existent_Function();
   };
   if ($@){
       ### catch block
       print "Failed \n";
   };
   print "end \n";

}}} OR use Error.pm for try/catch/finally syntax


Very basic Perl DBI script

{{{

  1. !/usr/bin/perl -w

use DBI;

      1. Connect to the database with Postgres driver
  1. my $connect_string = 'dbi:Pg:dbname=annotation;user=waynew;host=localhost;password=annotation';

my $dbh = DBI->connect( "DBI:Pg:dbname=annotation", "waynew", "annotation")

   or die "Got error $DBI::errstr when connecting to database\n";
      1. Prepare and Execute the statement in the database
  1. my $sth0 = $dbh->prepare( "SELECT regionid, label, ordinal from region" )

my $sth0 = $dbh->prepare( "SELECT annotationprojectid, name, space from annotationproject" )

   or die "Can't prepare SQL statement: $DBI::errstr\n";

$sth0->execute();

      1. Retrieve the returned rows of data

my @row; while ( @row = $sth0->fetchrow_array() ) {

   print "Project: @row\n";

} warn "Data fetching terminated early by error: $DBI::errstr\n"

   if $DBI::err;
      1. A delete statement

my $sth1 = $dbh->prepare( "INSERT INTO annotationproject (annotationprojectid, description, name, space) VALUES ('9', 'my description', 'project name here', '2')" )

   or die "Can't prepare SQL statement: $DBI::errstr\n";

$sth1->execute();

      1. Retrieve the returned rows of data

$sth0->execute(); while ( @row = $sth0->fetchrow_array() ) {

   print "Project: @row\n";

} warn "Data fetching terminated early by error: $DBI::errstr\n"

   if $DBI::err;


      1. Disconnect from database

$dbh->disconnect

   or warn "Error disconnecting: $DBI::errstr\n";

exit;

}}}

quickly check syntax of all .pl files in a directory: {{{ find . -name \*.pl -exec perl -c '{}' \; }}}

Data Structures cookbook:BR perldoc perldscBR Reference tutorial:BR perldoc perlreftut


Log the time

{{{ my @timeData = localtime(time); $timeData[4]++; print "$timeData[4]/$timeData[3], $timeData[2]:$timeData[1]\n";

  1. result: 7/21, 14:24

}}}

Personal tools