Posts Tagged ‘Perl – Coding Tips’

Perl – Coding Tips

Monday, March 23rd, 2009

Introduction

This document covers the basic functionalities in perl. These include the following:

·         Open and read file

·         Substring

·         Trim white spaces

·         Join string with/out delimiter

·         Remove newline

·         Split into array [reading key value pair]

·         String comparison and numeric comparison

·         Assign data in Hash or associative array and access the data

·         Write to and Close file

 

 

Open and Read file

 

To open and read a file, the read access to the file should be given.

 

open (<File identifier>,”<”,”<file>”)

or die “open failed:  $!”

 

File Identifier – After opening the file, the file will be referenced with the file identifier.

Symbol<’ – open a file in read mode

die – If open of the file failed, the program will display the error message and abort

 

$var=< File identifier>

 

E.g.: $var=’this is the first line of the file’

 

Read the first record (first line) from the file. Variable $var will hold the first line of the file.

 

@file_array=< File identifier >

 

The contents of the file can be assigned to an array

 

 

Substring

 

$substr_var=substr <string>, <start position>, <field length>

 

Get a substring of the first record from the file. The first record is stored in the variable $var.

 

In perl, the start position of a string is 0.

E.g.: If we need to cut first 5 characters from $var, start position will be 0 and field length will be 5.

$substr_var=substr $var, 0, 5

So, $substr_var=’this ‘

 

Note: Start position of a string in UNIX is 1.

 

 

Trim White Spaces

 

Substitute one or more white space characters with nothing from the end of the string (trailing spaces)

$variable =~ s/\s+$//

 

Substitute one or more white space characters with nothing from the beginning of the string (leading spaces)

$variable =~ s/^\s+//

 

Substitute one or more white space characters with nothing from anywhere in the string

$string =~ s/\s+//g

 

Substitute one or more white space characters with nothing from end and beginning of the string (leading and trailing spaces)

$test =~ s/^\s+|\s+$//g

         

         

Join string with/out delimiter

 

Join “”, <string 1>, <string2> [Join without any delimiter]

Output: <string1><string2>

 

Join “,”, <string 1>, <string2> [Join with ‘,’ delimiter]

Output: <string1>,<string2>

 

 

Remove newline

 

Substitute newline with nothing from the end of the string

$variable =~ s/\n+$//

 

chomp ($variable)

If variable is a hash, it chomps the hash’s values, but not its keys

 

 

Array [split on delimiter]

Array designated by @

 

@Arraytrial = (‘Trial’,’Array’)

$# Arraytrial=1 [largest index value]

 

To clean any array just set the largest index value to -1

$# Arraytrial = -1;

 

String can be put into array splitting it on a delimiter

@ Arraytrial = split(’,',$variable) [splitted on comma ‘,’]

          Split is an in built function which splits the string on the delimiter.

 

 

Data comparison

 

The comparison operator for numbers and strings are as follows:

 

Compare                   

Numbers      

String

Less than

lt

Greater than

gt

Less than equal

<=

le

Greater than equal

>=

ge

Equal

==

eq

Not equal

!=

ne

compare

<=>

cmp

         

 

 

Hash/Associative Array

Hash or associative array designated by %

 

Hashes contain data in pairs called KEY and associated VALUE

 

%names = (‘somali’,’444’,’arundhati’,’631’)

Or

% names = (somali         -> ‘444’,
                    arundhati     -> '631')
Or
my( %names);
$names{ <key> } = <value>

 

Print a hash

print “@{[% names]}”

 

 

 

Write and Close file

 

Open a file in write mode. Here if the file does not exist, the file will be created. If it exists, the file will be overwritten.

         

open (<File identifier>,”>“,”<file>”)

or die “open failed:  $!”

 

File Identifier – After opening the file, the file will be referenced with the file identifier.

Symbol>’ – open a file in write mode

die – If open of the file failed, the program will display the error message and abort

 

To append data into an existing file, the file needs to be opened in append mode.

 

open (<File identifier>,”>>“,”<file>”)

or die “open failed:  $!”

 

Symbol>>’ – open a file in append mode

 

To write to a file, write access to the file should be given.

 

print “$var\n” <File identifier>;

 

Close the file

 

close (<File identifier>)  

or die “close failed: $!”

 

 

Notes

 

There are many free Perl software are available on internet. Also you can use the UNIX command prompt just like unix scripts by using command “#!/usr/bin/perl” in script.

 

Reference(s)

http://docstore.mik.ua/orelly/perl/prog/ch01_05.htm

http://perldoc.perl.org/perlop.html

www.perl.com

www.perlfect.com

www.pageresource.com