Archive for the 'Perl' Category

Perl: Format date strings

Wednesday, December 7th, 2011

The other day I had a requirement to fill in a date value while creating an entity in ClearQuest. The field that was required was a date and was formatted as “mm/dd/yyyy hh:MM::SS AM|PM”. I used the localtime function to return the date and used sprintf to format the date to the proper output.
The reason I used sprintf was that for hours, months and days less 10 the output was 1 digit instead of two and the input was not allowed. The %02d states that the digits used will be a minumum of 2 in this case.

Here is the sample program I wrote to test the expected output:

 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;

# formatted just by concatenating output
my $datestring = $mon . "/" . $mday . "/" . $year . "  " . $hour . ":" . $min.
":" . $sec  ;

# formatted using sprintf to ensure proper digit counts are output
my $datestring2 = sprintf("%02d/%02d/%04d %d:%02d:%02d %s",$mon,$mday,1900 +$yea
r,$hour,$min,$sec, $hour >= 12? "PM" : "AM");

 print $datestring;
  print $datestring2;

Tags: ,

Perl: Open and read file line by line

Wednesday, September 28th, 2011

I regularly have to process Comma Seperated Value or CSV files, usually for user lists. So the following perl code is a framework for processing a file line by line.

#!/usr/bin/perl
use strict;
my $line;

open(FILEIN, "filename.txt");

while(<FILEIN>)
{
  chomp();
  $line = $_;
  # Process $line for data
  # Example seperating line by commas: 
  my ($username,$firstname,$lastname,$email) = split(/,/,$line);
}

close(FILEIN);

Tags: ,

Perl: Hashes

Wednesday, September 7th, 2011

Here are some basics about Perl hashes that can be helpful to be used when an you need to associate a label with some value such as for names and telephone numbers or account numbers with amounts owed.

Create a hash variable.

my %hashvar;

Create a hash reference

my $refhash = {};

Add a value to a hash variable.

$hashvar{'somekey'} = 'someval';

Add a value to a hash reference.

$hashref->{'somekey'} = 'someotherval';

Access a value in a hash.

print $hashvar{'somekey'};

Access a value in a hash reference.

print $hashref->{'somekey}';

Access all Keys in a hash variable.
foreach my $k (keys(%hashvar))
{
print $hashvar{$k};
}

Access all Keys in a hash reference.

foreach my $k (keys(%$hashref))
{
  print $k . "n";
}

Access all Keys and values in a hash.

while (my ($key,$value) = each %hashvar)
{
  print "Key: " . $key . " has value:" . $value . "n";
}

Access all Keys and values in a hash.

while (my ($key,$value) = each %$refhash)
{
  print "Key: " . $key . " has value:" . $value . "n";
}

Assigning multiple values to a hash

%hasvar = (
  'test2' => 'myval',
  'test3' => 'myval3'
);

Note: This will clear the existing hash.

Delete a value from a hash

delete $hashvar{'key1'};

Delete a value from a hash reference.

delete $hashref->{'key1'};

Tags: , , ,

Perl: Arrays

Saturday, September 3rd, 2011

I use perl arrays in some of my programs, and just started to look at the regular things that I do with these arrays and thought it would be useful to keep a list of frequently used items.

Create a variable specified as an array.

my @vararray

Add an item to the beginning of an array

unshift (@vararray, "File2");

Add an item to the end of an array

push (@vararray, "File1");

Remove an item from the beginning of an array

my $var = shift(@array);

Remove an item from the end of an array

pop(@array)

Clear an array

@vararray = ();

Address an item in an array

print $vararray[0] ; 

Get the size of an array

my $arraysize = @array;

Remove an item based on the index

delete @vararray[1];

Iterate over an array

foreach my $var (@vararay)
{
  print "$var n";
}
 
# or 
my $size = @vararray;
my $i;
for ($i = 0 ; $i < @size; $i++)
{
  print "$vararray[$i]n";
}

Tags: , ,

How to add library paths to perl

Saturday, August 13th, 2011

I need to write custom Perl libraries sometimes and an easy method to make sure that they are found on the path is to use the PERL5LIB environment variable.

So either set it in your current environment or in a shell you can just specify the contents before you run your script.

PERL5LIB=/PATH/WHERE/LIB/IS perl scripttorun.pl 

Tags: ,

Perl: CPAN installing modules

Friday, August 5th, 2011

Sometimes it is necessary to install other modules into the Perl environment. Luckily there is a great repository of modules known as CPAN (The Comprehensive Perl Archive Network). This lets you install modules to help with encryption, XML,YAML, and many other things. There are a few ways to install a package and here are the ones that I use the most.

Using the CPAN shell:

perl -MCPAN -e shell

This will open a command prompt that will let you search for CPAN modules with:

i /PACKAGENAME/

or install a new module:

install /DateTime/

The nice thing about installing with CPAN is that it will look for the dependencies and suggest installing them before the module you requested.

NOTE:This can take some time and your dependencies could have dependencies.

The other method I use is to skip the CPAN prompt and just directly execute the install of the module:

perl -MCPAN -e 'install DateTime'

This is just the most basic of usage, and there is probably a lot more you can do, but I have not had to use much more than this.

Tags: , ,

Gallery of Hello World!

Thursday, August 4th, 2011

Here is a list of the Hello World Programs for different languages:

C

#include <stdio.h>
int main()
{
printf("Hello World!");
}

C++

#include <iostream.h>
int main()
{
cout << "Hello World!" << endl;
}

C#

public class HelloWorld
  public static void Main()
  {
    System.Console.WriteLine("Hello World!");
  }

Java

class HelloWorld {
static void main(String[] args)
{
System.out.println("Hello World!");
}

SHELL

echo "Hello World"

Python 2

print "Hello World!\n"

Python 3

print ("Hello World!")

Ruby

puts "Hello World!"

Perl

print "Hello World!n";

PHP

  <?php      
    print "Hello World!";
  ?>

Rust

fn main() {
    println("Hello World!");
}

This is the simplest form of Hello World for most of these languages.

Tags: , , , , , , ,

Testing perl modules

Wednesday, January 5th, 2011

A quick way to test a perl module with a new method is to use a command like the following:

$ perl -MeTechTips::IssueTracking::ClearQuest -we '$tr =  eTechtips::IssueTracking::ClearQuest->new();'

This will test the new and ensure that you have the correct syntax if you do not have an easy test environment for your code, for example as I do not have a ClearQuest instance to test with.

Perl find location of a library

Friday, December 24th, 2010

If you are not sure of the location of where a library is being included from in Perl you can use the following command:

perl -MXML::SAX -le 'print $INC{"XML/SAX.pm"}'

This search is for the XML::SAX library and it displays the location of the SAX.pm file.

Perl: Missing ParserDetails.ini

Friday, December 24th, 2010

I have some scripts that were giving me the following message:
could not find ParserDetails.ini in /usr/lib/perl5/vendor_perl/5.10/XML/SAX

The way that I worked around this message was to create the ParserDetails.ini file in the /usr/lib/perl5/vendor_perl/5.10/XML/SAX directory with the following contents.

[XML::SAX::PurePerl]
http://xml.org/sax/features/namespaces = 1

Tags: ,