Introdcution of Perl

What is Perl

  1. Perl is a programming language, It’s Object Oriented, simple to learn and very powerful. Perl stand for: “Practical Extraction and Reporting Language”.
  2. Perl is an Interpreted language, so you don’t have to compile it like you do Java, C, C++ etc. For fast development work, that’s a godsend.
  3. Perl is a versatile, powerful programming language used in a variety of disciplines, ranging from system administration to web programming to database manipulation.
  4. Perl is a different language to different people. It is a quick scripting tool for some, and a fully-featured object-oriented language for others.
  5. Perl is used in so many places because Perl is a glue language. A glue language is used to bind things together.
  6. Perl is good at is tying these elements together. Perl can take your database, convert it into a spreadsheet-ready file, and, during the processing, fix the data if you want.
  7. Perl can also take your word processing documents and convert them to HTML for display on the Web.

WHY PERL.

There are a many reasons why Perl is a great language for use in development and general processing.
Following are some of them…

  • Learning: Perl has all the same abilities, data constructs and methods of other languages, and its easier to learn then most. If you understand Perl, you will have far less trouble learning other languages like C, C++, Java, PHP etc then if you were starting from scratch.
  • Interpreted language means less time spent debugging.
  • Mod_perl for CGI work means perl can be as fast as compiled languages without the need to manually compile. mod_perl is an advanced implementation of Perl that runs in the Apache web server. It provides extremely fast performance and full access to Apache internals via Perl.
  • CPAN.org, a massive collection of perl modules that can do almost anything, someone has usually done the work for you. CPAN, the Comprehensive Perl Archive Network, is one of the largest repositories of free code in the world. If you need a particular type of functionality, chances are there are several options on the CPAN, and there are no fees or ongoing costs for using it.
  • Online support. Perl has been around since the early 90’s, its exceptionally well known and thousands of tutorial and help sites abound on the internet. Perl has a very strong user community and this is the primary avenue for support.
  • ISP support. Perl runs on nearly anything, it comes standard on the vast majority of unix/linux servers and is available free for windows servers. As a result its the most commonly supported language on ISP (Internet Service Providers) hosting servers.
  • Text processing. Because perls’ initial reason for living was text processing, its regular expression engine is exceptionally powerful. That means advanced text manipulation is easier then ever. (And let’s face it; nearly all programming is text manipulation of some sort.
  • Database connectivity. Thanks to the DBI module, perl can talk to a great many different databases with the same syntax. That means that you only have to learn one interface to talk to over a dozen different database servers. That’s as opposed to learning each DB’s syntax and commands seperately. Perl provides an excellent interface to nearly all available databases, along with an abstraction layer that allows you to switch databases without re-writing all of our code.
  • Freebies. Since Perl has been around for ages, there are thousands of scripts on the internet that are free to use and/or modify. Perl, Apache, and related technologies are open source and free. On-going overhead cost to vendors for code that continues to run is $0.
  • Multi-platform: Perl runs on Linux, MS Windows and all of the platforms listed here: http://www.cpan.org/ports/external link
  • Rich Community Support: The main point of these stats is that Perl has a large and broad user community. With any technology you choose, you don’t want to be the only one using it. These numbers show that Perl is still widely used for web development, among other things, and the user community is very active.
  • Re-usable code architecture (modules, OO, etc.): Perl is architected to allow and encourage re-use. The core block of re-use, the module, makes it very easy to leverage business logic across platforms in web applications, batch scripts, and all sorts of integration components.
  • Multi-use: Perl can be used to develop Web apps, batch processing, data analysis and text manipulation, command-line utilities and apps, GUI apps.
  • Multi-language integration: can interact with C, C++, Java, etc. from within Perl code.

WHY NOT PERL.

All languages have areas that they excel in, and others that they don’t. Perl is no different. Technically, you could write anything in Perl, even a complete operating system. but that does not mean you should. Its a matter of considering your requirements and deciding on the best language to suit them. Here are some reasons why Perl might not be your best choice:

  • Speed. If for example, you were writing a huge word processer like MS Word or WordPerfect. the sheer size of it would make it extremely slow to compile at runtime. For this you would be much better served by a language like C or C++ where the compilation is done before you run it.

Reference:

http://www.scmgalaxy.com/component/content/article/64-perl/223-introduction-of-perl.html

Tagged : / / / / /

Perl function to remove any element using value validation

rajeshkumar created the topic: perl function to remove any element using value validation
perl function to remove any element using value validation

Not Working –

my @items = (rajesh1, rajesh2,rajesh3,rajes4,rajesh5,rajesh7)
my $index = 0;
for my $value (@items) {
print "testing $value\n";
if ( $value == "rajesh1" or $value == "rajesh2" or $value == "rajesh3") {
print "removed value $value\n";
splice @items, $index, 1;
}
$index++;
}
print "@items"

Not Working

my @items = (rajesh1, rajesh2,rajesh3,rajes4,rajesh5,rajesh7)
my $element_omitted = "rajesh1";
@items = grep { $_ != $element_omitted } @items;
print "Value of @items";

Trying this now.

my $index = 0;
while ($index <= $#items ) { my $value = $items[$index]; print "testing $value\n"; if ( $value == 1 or $value == 3 ) { print "removed value $value\n"; splice @items, $index, 1; } else { $index++; } }

Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

Tagged :

Foreach Vs for Vs while in perl

rajeshkumar created the topic: foreach Vs for Vs while in perl

Definition 1:
In the while loop, Perl reads a line of input, puts it into a variable, and runs the body of the loop. Then, it goes back to find another line of input.

But in the foreach loop, the line-input operator is being used in a list context (since foreach needs a list to iterate through). So it has to read all of the input before the loop can start running.

That difference will become apparent when the input is coming from your 400 MB web server logfile! It’s generally best to use code like the while loop’s shortcut, which will process input a line at a time, whenever possible. Source-The Llama book

Definition 2:
What Alex Reynolds says in stackoverflow.com
For most purposes, you probably won’t notice a difference.
However, foreach reads each line into a list (not an array) before going through it line by line, whereas while reads one line at a time.
As foreach will use more memory and require processing time upfront, it is generally recommended to use while to iterate through lines of a file.

In addition to the previous responses, another benefit of using while is that you can use the $. variable. This is the current line number of the last filehandle accessed

while ( my $line = ) {
if ( $line =~ /some_target/ ) {
print "Found some_target at line $.\n";
}
}

Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

Tagged :

Commonly Used Sign- Punctuation and their Name in Perl

perl-sign-punctuation-marks

Commonly Used Sign- Punctuation and their Name in Perl

( => ) Comma Arrow  ( ‘ ’, “ ”, ‘ ‘, ” “ ) à Quotation marks
( $ ) àDollar sign ( ~ ) à Tilde
( % ) àPercent sign ,  ) à Comma
( @ ) à At Sign ( ; ) à Semicolon
( & ) à Ampersand Sign ( : ) à Colon
( / ) à Forward Slash/Slash sign ( , , ) à Dash
( \ )  à Backslash/Slash Sign ( )    à Hyphen-minus
( < )  à Less than Sign ( _ ) àunderscore
( > )  à Greater than sign ( / ) à slash/stroke/solidus
( { } )  àCurly Braces ( * ) à Asterisk
( [  ] ) à Square brackets ( ^ ) à caret
( ( ) )  à Round brackets ( ¦, | ) à vertical bar/broken bar/pipe
( , , ) àprime ( ) à Ditto mark
( ! ) à Exclamation Mark ( ? ) – Question Mark
Tagged : / / / / / / / / / / / / / / / / /

How to Execute external commands by using perl?

execute-external-commands-from-perl

There are many ways to execute external commands from Perl. The most commons are:

  • system function
  • exec function
  • backticks (“) operator
  • open function

All of these methods have different behaviour, so you should choose which one to use depending of your particular need. In brief, these are the recommendations:

method use if …
system() you want to execute a command and don’t want to capture its output
exec you don’t want to return to the calling perl script
backticks you want to capture the output of the command
open you want to pipe the command (as input or output) to your script

More detailed explanations of each method follows:

Using system()
system() executes the command specified. It doesn’t capture the output of the command.
system() accepts as argument either a scalar or an array. If the argument is a scalar, system() uses a shell to execute the command (“/bin/sh -c command”); if the argument is an array it executes the command directly, considering the first element of the array as the command name and the remaining array elements as arguments to the command to be executed.
For that reason, it’s highly recommended for efficiency and safety reasons (specially if you’re running a cgi script) that you use an array to pass arguments to system()

Example:      #-- calling 'command' with  arguments    system("command arg1 arg2 arg3");         #-- better way of calling the same command    system("command", "arg1", "arg2",  "arg3");     The return value  is set in $?; this value is the exit status of the command as returned  by the 'wait' call; to get the real exit status of the command you have to  shift right by 8 the value of $? ($? >> 8).     If the value of $? is -1, then the command failed to execute, in that case you may check the value  of $! for the reason of the failure.
Example:      system("command",  "arg1");    if ( $? == -1 )    {      print "command failed: $!\n";    }    else    {      printf "command exited with value %d", $? >> 8;    }

Using exec()
The exec() function executes the command specified and never returns to the calling program, except in the case of failure because the specified command does not exist AND the exec argument is an array.
Like in system(), is recommended to pass the arguments of the functions as an array.

Using backticks (“)
In this case the command to be executed is surrounded by backticks. The command is executed and the output of the command is returned to the calling script.
In scalar context it returns a single (possibly multiline) string, in list context it returns a list of lines or an empty list if the command failed.
The exit status of the executed command is stored in $? (see system() above for details).

Example:      #-- scalar context    $result = `command arg1 arg2`;         #-- the same command in list context    @result = `command arg2 arg2`;     Notice that the  only output captured is STDOUT, to collect messages sent to STDERR you should  redirect STDERR to STDOUT
Example:      #-- capture STDERR as well  as STDOUT    $result = `command 2>&1`;

Using open()
Use open() when you want to:
– capture the data of a command (syntax: open(“command |”))
– feed an external command with data generated from the Perl script (syntax: open(“| command”))

Examples:      #-- list the processes  running on your system    open(PS,"ps -e -o pid,stime,args |") || die "Failed: $!\n";    while ( <PS> )    {      #-- do something here    }         #-- send an email to user@localhost    open(MAIL, "| /bin/mailx -s test user\@localhost ") || die  "mailx failed: $!\n";  print MAIL "This is a test message";
Tagged : / / / / / / / / / / / / / / /

Difference between use and require in Perl – use Vs require in perl

perl-use-require-difference

|| use Vs require in perl || What is the difference between use and require?

Except of course that use is evaluated at compile time where as require is evaluated at run time in other word, A use anywhere in the code will be evaluated when the code is run compiled, but require – import’s can only get evaluated when encoutered.

The differences are many and often subtle:

  1. use only expects a bareword, require can take a bareword or an expression
  2. use is evaluated at compile-time, require at run-time
  3. use implicitly calls the import method of the module being loaded, require does not
  4. use excepts arguments in addition to the bareword (to be passed to import), require does not
  5. use does not behave like a function (i.e can’t be called with parens, can’t be used in an expression, etc), whereas require does

do $file is like eval `cat $file`, except the former:
1.1: searches @INC and updates %INC.
1.2: bequeaths an *unrelated* lexical scope on the eval’ed code.

require $file is like do $file, except the former:
2.1: checks for redundant loading, skipping already loaded files.
2.2: raises an exception on failure to find, compile, or execute $file.

require Module is like require “Module.pm”, except the former:
3.1: translates each “::” into your system’s directory separator.
3.2: primes the parser to disambiguate class Module as an indirect object.

use Module is like require Module, except the former:
4.1: loads the module at compile time, not run-time.
4.2: imports symbols and semantics from that package to the current one.

Command to learn more about use and require
> perldoc -f require
> perldoc -f use

Tagged : / / / / / / / /

How to Check File Attributes in Perl ? Perl File Attributes explained

perl-file-attributes

Checking File Attributes in Perl

I have been using perl for quite some time now. I have also been using the file handling logic in my scripts. However, what I did not know till now is that you can quickly check for certain file properties in perl. Here is an example:
#!/usr/bin/perl
my (@description,$size);
if (-e $file)
{
push @description, ‘binary’ if (-B _);
push @description, ‘a socket’ if (-S _);
push @description, ‘a text file’ if (-T _);
push @description, ‘a block special file’ if (-b _);
push @description, ‘a character special file’ if (-c _);
push @description, ‘a directory’ if (-d _);
push @description, ‘executable’ if (-x _);
push @description, (($size = -s _)) ? “$size bytes” : ‘empty’;
print “$file is “, join(‘, ‘,@description),”\n”;
}
Nice, isn’t it?
Here is the complete list of features that you can check:

Operator Description
-A Age of file (at script startup) in days since modification.
-B Is it a binary file?
-C Age of file (at script startup) in days since modification.
-M Age of file (at script startup) in days since modification.
-O Is the file owned by the real user ID?
-R Is the file readable by the real user ID or real group?
-S Is the file a socket?
-T Is it a text file?
-W Is the file writable by the real user ID or real group?
-X Is the file executable by the real user ID or real group?
-b Is it a block special file?
-c Is it a character special file?
-d Is the file a directory?
-e Does the file exist?
-f Is it a plain file?
-g Does the file have the setgid bit set?
-k Does the file have the sticky bit set?
-l Is the file a symbolic link?
-o Is the file owned by the effective user ID?
-p Is the file a named pipe?
-r Is the file readable by the effective user or group ID?
-s Returns the size of the file, zero size = empty file.
-t Is the filehandle opened by a TTY (terminal)?
-u Does the file have the setuid bit set?
-w Is the file writable by the effective user or group ID?
-x Is the file executable by the effective user or group ID?
-z Is the file size zero?
Tagged : / / / / / / / / / / / / / / /

Introduction of Perl – Complete Overview

perl-introduction

What is Perl

  1. Perl is a programming language, It’s Object Oriented, simple to learn and very powerful. Perl stand for: “Practical Extraction and Reporting Language”.
  2. Perl is an Interpreted language, so you don’t have to compile it like you do Java, C, C++ etc. For fast development work, that’s a godsend.
  3. Perl is a versatile, powerful programming language used in a variety of disciplines, ranging from system administration to web programming to database manipulation.
  4. Perl is a different language to different people. It is a quick scripting tool for some, and a fully-featured object-oriented language for others.
  5. Perl is used in so many places because Perl is a glue language. A glue language is used to bind things together.
  6. Perl is good at is tying these elements together. Perl can take your database, convert it into a spreadsheet-ready file, and, during the processing, fix the data if you want.
  7. Perl can also take your word processing documents and convert them to HTML for display on the Web.

WHY PERL.

There are a many reasons why Perl is a great language for use in development and general processing.
Following are some of them…

  • Learning: Perl has all the same abilities, data constructs and methods of other languages, and its easier to learn then most. If you understand Perl, you will have far less trouble learning other languages like C, C++, Java, PHP etc then if you were starting from scratch.
  • Interpreted language means less time spent debugging.
  • Mod_perl for CGI work means perl can be as fast as compiled languages without the need to manually compile. mod_perl is an advanced implementation of Perl that runs in the Apache web server. It provides extremely fast performance and full access to Apache internals via Perl.
  • CPAN.org, a massive collection of perl modules that can do almost anything, someone has usually done the work for you. CPAN, the Comprehensive Perl Archive Network, is one of the largest repositories of free code in the world. If you need a particular type of functionality, chances are there are several options on the CPAN, and there are no fees or ongoing costs for using it.
  • Online support. Perl has been around since the early 90’s, its exceptionally well known and thousands of tutorial and help sites abound on the internet. Perl has a very strong user community and this is the primary avenue for support.
  • ISP support. Perl runs on nearly anything, it comes standard on the vast majority of unix/linux servers and is available free for windows servers. As a result its the most commonly supported language on ISP (Internet Service Providers) hosting servers.
  • Text processing. Because perls’ initial reason for living was text processing, its regular expression engine is exceptionally powerful. That means advanced text manipulation is easier then ever. (And let’s face it; nearly all programming is text manipulation of some sort.
  • Database connectivity. Thanks to the DBI module, perl can talk to a great many different databases with the same syntax. That means that you only have to learn one interface to talk to over a dozen different database servers. That’s as opposed to learning each DB’s syntax and commands seperately. Perl provides an excellent interface to nearly all available databases, along with an abstraction layer that allows you to switch databases without re-writing all of our code.
  • Freebies. Since Perl has been around for ages, there are thousands of scripts on the internet that are free to use and/or modify. Perl, Apache, and related technologies are open source and free. On-going overhead cost to vendors for code that continues to run is $0.
  • Multi-platform: Perl runs on Linux, MS Windows and all of the platforms listed here: http://www.cpan.org/ports/external link
  • Rich Community Support: The main point of these stats is that Perl has a large and broad user community. With any technology you choose, you don’t want to be the only one using it. These numbers show that Perl is still widely used for web development, among other things, and the user community is very active.
  • Re-usable code architecture (modules, OO, etc.): Perl is architected to allow and encourage re-use. The core block of re-use, the module, makes it very easy to leverage business logic across platforms in web applications, batch scripts, and all sorts of integration components.
  • Multi-use: Perl can be used to develop Web apps, batch processing, data analysis and text manipulation, command-line utilities and apps, GUI apps.
  • Multi-language integration: can interact with C, C++, Java, etc. from within Perl code.

WHY NOT PERL.

All languages have areas that they excel in, and others that they don’t. Perl is no different. Technically, you could write anything in Perl, even a complete operating system. but that does not mean you should. Its a matter of considering your requirements and deciding on the best language to suit them. Here are some reasons why Perl might not be your best choice:

  • Speed. If for example, you were writing a huge word processer like MS Word or WordPerfect. the sheer size of it would make it extremely slow to compile at runtime. For this you would be much better served by a language like C or C++ where the compilation is done before you run it.

 

Tagged : / / / / / / / / / / / /