May 15, 2012

send email in perl

There are 3 ways to send mail from Perl
  • shelling out to /usr/sbin/sendmail
  • using Net::SMTP directly when the application did not need to send attachments
  • using MIME::Lite when you did need to include attachments

Out of these MIME::Lite is best as it handles attachments and performance perspective.
Let us explain sending email using MIME::Lite 


#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use MIME::Lite;

    my $msg = MIME::Lite->new(
        From     =>'admin@example.com',
        To       =>'user@example.com',
        Subject  =>'testing a mail with attachments',
        Type =>'multipart/mixed'
    ) die "Error creating multipart container: $!\n";
  
    ### Add the text message part
    $msg->attach (
      Type => 'TEXT',
      Data => "Here is the attachment file(s) you wanted"
    ) or die "Error adding the text message part: $!\n";

    ### Add the GIF file
    $msg->attach (
       Type => 'image/gif',
       Path => my_file.gif,
       Filename => your_file.gif,
       Disposition => 'attachment'
    ) or die "Error adding $file_gif: $!\n";

    ### Add the ZIP file
    $msg->attach (
       Type => 'application/zip',
       Path => my_file.zip,
       Filename => your_file.zip,
       Disposition => 'attachment'
    ) or die "Error adding $file_zip: $!\n";

       $msg->send;

1;





Delete logs older than 7 days

#! /usr/bin/perl

use strict;
use warnings;
#use CGI;
#use CGI::Carp qw(fatalsToBrowser);   
use Data::Dumper;

foreach my $file (</test/logs/log_*.txt>) {   
    if ( -M $file > 7 ) {
        print "\n Deleting the log file more than 7 days old: " . $file;
        unlink $file; #or die "\nFailed to remove $file: $!";
    }
}

print "\n\n";


1;


Note:
  • The above program is based on the time stamp of the files. 
  • The program detects files staring with 'log_' format and deletes these files whose time stamp of the file is greater than 7 days (since the current time stamp).
  • '-M' is used to check the timestamp
  • 'ulink' is used to remove file 
  • Please change the corresponding shebang line  (#! /usr/bin/perl) if you are using windows environment to test this perl script
  • In the above example, in the specified path (/test/logs/) I have some files like... Let us assume we have files like this 
log_1.txt (7 days old)
log_2.txt (8 days old)
log_3.txt (9 days old)
log_4.txt (10 days old)
log_5.txt (3 days old)
log_6.txt (4 days old)
error_log.txt (10 days old)
server_log.txt (10 days old)

Program Output: The program will delete files
log_1.txt, log_2.txt, log_3.txt, log_4.txt

Since the files 'error_log.txt' and 'server_log.txt' won't start with 'log_' the program don't delete them irrespective of the timestamp.


May 14, 2012

Perl Books

Please find all the Perl books at one place. For Perl, O'Reilly series books are well known.

As a Perl developer, I have personally gone through books of O'Reilly series books and I found those books are informative and useful for my career as a developer.

I have gone through books like Programming Perl, Perl Best Practices, Mastering Regular Expressions etc.,

Note: Please note that I am not marketing O'Reilly books in anyway. Its my personal opinion.

For your ease, I am keeping the collection of Perl books at one place, please go through.


Learning Perl :




Programming Perl :


Intermediate Perl :




Mastering Perl :
Link to be updated.....

Begenning Perl :


Perl Best Practices:


Object Oriented Perl:


Minimal Perl:


Perl Hacks:


Perl CookBook


Perl for Dummies:


Advanced Perl Programming:


Automating System Adminstration with Perl:



Mastering Regular Expressions:


Regular Expressions Cookbook:

May 11, 2012

Non Capturing Paranthesis (?:) in Regular Expressions

From my earlier blog on capturing, you might have understood about the capturing concept in regular expressions.

Let us now look the Non-capturing concept in regular expressions with a simple example

To achieve non-capturing parenthesis use "?:" 

E.g.  $input = +456.987c
        $input = ~/([-+]?[0-9]+(?:\.[0-9]*)?)([cf])$/     
   
     Where  $1 = ([-+]?[0-9]+(\.[0-9]*)?) #which matches '456.987'
                  $2 = ([cf])                                #which matches 'c'




Carefully observe, here
$2 is not (?:\.[0-9]*) but instead it is ([cf]), why because (?:\.[0-9]*) is starting with ?: which means it is not being captured, so $2 becomes ([cf])
                     
Advantages of Non-Capturing:
    1) Avoids unnecessary Capturing (Matches only what ever required)
    2) Efficiency Enhancement



Please refer to my earlier blog on capturing

I will be discussing about "Look Around" concepts of regular expressions in my coming blog.

Don't hesitate to comment if you have any doubts or queries on this topic.

Thanks for your valuable time and have a great day :-)


May 9, 2012

Capturing in Regular Expressions

Parenthesis inside regex will be grouped as well as captured.
Let me explain the grouping concept with an example where in you want to validate a decimal part

Eg: Validation for decimal part as given in the below mentioned example

        $input = +345.34f
        $input = ~/([-+]?[0-9]+(\.[0-9]*)?)([cf])$/
        where
                  $1 = /([-+]?[0-9]+(\.[0-9]*)?)    # 345.34
                  $2 = (\.[0-9]*)                            # .34
                  $3 = ([cf])                                  #  f

Notations used in the above example :
1) $1, $2, $3 are grouping data, one can capture the specific data and use it later in the program with $1, $2, $3 etc.,
2) *, + are greedy operators, they match more than what they required, that's why they are called as Greedy Operators
3) ? is a limiting operator which limits the mapping to what ever required
4) [] is a character class
5) $2 lies within $1 even then they both are distinct
6) $ represents the end of the string

Advantages of capturing:
 a) You can capture the data and use the data later in the program
 b) Very useful when we want to grep or capture tricky regex

Disadvantages of unnecessary Capturing:
 a) Waste of memory.
 b) Performance problem.
 c) Regex will be costlier


I hope you have really liked today's topic.

Please share your views with me in case of any any doubts/suggestions. Feel free, don't hesitate :-)

I will be explaining about the Non-Capturing Parenthesis in my next blog. Keep watching my blog.

Thanks for your valuable time. Have a good day :-)

May 4, 2012

Regular expressions or Regex or Regexp

Regular Expressions are some patterns describing some amount of text.

Real World Application of Regular Expressions:
Suppose you have a file that contains comma separated employee details like
First name, Last name, Cell no, Salary, address, Email etc.,
1) You want to extract only the Employee name and email-id from that huge list of data.

2) You are looping through the employee details, you just want to pick all the employees info whose salary is greater than 5000$
3) You want to replace all the occurrences of a misspelled employee name
e.g., Grorge to George

And lot more............



Advantages of Regular Expressions:
1) Regular expressions is a part and parcel in Perl.
2) It makes the life easy for a developer or programmer to search/replace a pattern in a line.
3) It saves a lot of time of the developer or programmer


General Topics on Regular Expressions:
1) Search & Replace
2) Start and End of String or Match
3) Word Boundaries etc.,


Advanced Topics on Regular Expressions:
1) Capturing
2) Non-Capturing PAranthesis
3) Look Around Concepts
4) Look Ahead
5) Look Behind
6) Back Tracking
7) Atomic Grouping
8) Possessive Quantifiers etc.,

We will discuss these topics one by one in brief in the coming posts.
Thanks for your valuable time, Have a good day :-)