Realworldnumbers

Permutations of seemingly innocuos musings, and strange guesstimations.

Useful Perl Concepts and Examples April 1, 2008

Here’s a list of useful Perl concepts and examples that I have compiled for my brother, and anyone else who might have an interest in Perl.

If there’s any examples you’d like to see or you have something useful for others, please comment!  Thanks!

I use perl all the time at the telecommunications company where I work. I use it to process Gigabyte-large files with complex algorithms, gathering hourly statistics off of remote devices, and to identify patterns.

Ordinarily, I don’t publish such geeky content, but considering it’s been a while since my last post, and that my brother has taken an active interest in scripting, I decided to put this out there, for posterity sake.

Enjoy!

Concept 1 – Perl date and time.

Usually when I start off a script, I love to print out the time. I also print out the time at the end of a script. t helps me to benchmark the efficiency of my code, and estimate large jobs (sometimes running for 9 hours straight on large text files).

Example:

# Use external Libraries
use Time::Local;

## Print out the time
print “+————–This script started on: “.`date`.”<BR>”;

Concept 2 – Perl File I/O – File Output

Hint! Make sure that your filename doesn’t already exist (if it does, you will overwrite), that you have permissions to create the file in the directory you have specified.

Example:

$workingdir=”/path/to/here/”;
$filename=”filename.txt”;
open( FILE, “> $workingdir/$filename” ) or die “Can’t open $workingdir/$filename : $!”;

print FILE “this is awesome”;

close (FILE);

Concept 3 – Per File I/O – File Input

File I/O is great. Here’s a hint to speed up operations done on a large text file – read the complete file (no matter how big) into an array, then work with that array. Working with a file handle is slow, as disk reads and writes are significantly slower than RAM.

Example:

open(DATA,”<import.txt”) or die “Can’t open data”;
@lines = <DATA>;
close(DATA);

Concept 4 – Chomp!

Sometimes when you suck a file into a variable, it brings some of the nasty stuff along with it. Case in point, the end-of-line invisible carriage return character. If you ever want to get rid of it, use chomp(). It’s easy. The chomp() function actually modifies the variable, so only 1 argument is needed… the variable name!

Example:

chomp($line);

Concept 5 – Splitting a delimited line into usable variables

Consider you have a comma-delimited text file, and you wish to print only the first name field of a line

Example line:

2008,04,01,Peppers,Muffy,123 Real Street, Ontario, Canada

You would suck the file into an array called @lines, and run a loop where you split each line, printing only the fifth segment (line 0×04). Note the use of the $_ , this means “THIS”. “THIS” is whatever is being returned by the loop. In this case, THIS means “each line of the file”.

foreach (@lines){

@lineparse=split(/,/, $_);

print “After splitting, we can display individual columns like this: $lineparse[0], $lineparse[1], $lineparse[2], $lineparse[4]\n”;
};

Concept 6 – Using external libraries to do cool things

Perl has lots of available modules you can use to plug in functions that you just don’t feel like programming yourself. This can be mathematical, formatting, file functions, creating graphs, interactive TCP port functions, network functions (like packet crafting, ftp sessions, automated telnet, etc.).

They’re pretty easy to use. First, identify what you need. In this case, I shall be installing a library to telnet into a device interactively, run a command, and store the output of that command into a variable which I can print out somewhere. The CPAN pages will have examples.

  1. Download a module to your local computer. In this case Net::Telnet.
  2. Install.
    perl Makefile.PL
    make
    make test
    make install
  3. Modify your code to use it.

Example code to use after installing your module:

# Use external Libraries
use Net::Telnet;

$telnet = new Net::Telnet ( Timeout=>10,
Errmode=>’die’,
Prompt => ‘/#/i’);
$telnet->max_buffer_length(80000000);
$telnet->open($IP_address);
$telnet->login($username, $password);

## Issue a command without caring what the response is
$telnet->cmd(’cd /etc/’);


## Issue a command and show the output
print $telnet->cmd(String => “cat /etc/passwd”, Timeout => 600);

close (telnet);

Concept 7 – Passing command line arguments to the perl script.

$firstargument = $ARGV[0] or die “didn’t pass an argument”;
$secondargument = $ARGV[1] or die “didn’t pass an argument”;

 

8 Responses to “Useful Perl Concepts and Examples”

  1. Tina Russell Says:

    I finally decided to write a comment on your blog. I just wanted to say good job. I really enjoy reading your posts.

    Tina Russell

  2. gabywife Says:

    Nice, very nice, love it….i’m learning!!!I do! xoxox

  3. Radha Says:

    Hello,

    I enjoyed the way you have written the post. I am new to perl and it helped me a lot.

    Thanks,
    Radha

  4. realworldnumbers Says:

    Hi Radha, so glad you enjoyed… sometimes it’s nice to just have a quick reference or primer on the subject. Thanks for stopping by!

  5. Vel Says:

    Hi,
    Thanks to you for posting perl concepts. The way you presenting the concepts are easy to understand. Thanks lot. It would be very useful if you add some more concepts.

    Thanks,
    -Vel Nadukuppam

  6. nick Says:

    cJlFMc hi! hice site!

  7. Harika Says:

    This page helped me lot. :)
    Thanks ………………….

  8. Thanks for your compliment


Leave a Reply