Perl My View

How I used perl, what is my understanding about perl. It's not necessary everything is right, what i am writing here. I need comments from reader, so I can improve my understandings.


Command-line arguments
#argument variable
my $arg1 = $ARGV[0];
my $arg_num = $#ARGV+1;

foreach $argnum (0 .. $#ARGV) {
   print "$ARGV[$argnum]\n";
}
Check perl file syntax
perl -c perlfile.pl
Include perl module 
#!/usr/bin/perl -I module_path
Perl module format or .pm file format.
#first line :
package pakcage_name;
#last line :     this means when module load it should return true, otherwise its through compilation error.
1

#when you want to use any Module
use moudle_name;
use XML::Simple;
use Data::Dumper;

File handling
writting
open(FILEHANDLE,">$filename"); # for overwritting, for append use >>, for reading <
print FILEHANDLE $content    # no comma between filehandle and reading or writing variable
close(FILEHANDLE);
reading
open INPUT, "<$filename";
while ( <INPUT> ) {           # read line  by line
        print $_;
}

======================================================================


======================================================================
remove duplicate/get unique lines from file
my %lines;
open INFILE, "dupfile.txt"  or die "Couldn't open file: $!";
my $n=0, $nn=0;
while(<INFILE>){
        my $line = $_;
        $n =$n+1;
        if ( !exists $lines{$line}){
                $lines{$line}=$line;
                $nn = $nn+1;
        }
}
foreach $id (keys %lines){
        print STDOUT $id;
}
print STDOUT "lines ".$n." users ".$nn."\n";


subroutines format
sub mysub
{
my ($param1,$param2) = @_;  # one line get all parameter
my $param1 = $_[0];   # get parameter one based on index

$ret;   # last statement is default return statement.
}
print formated output
print <<OUT;
<Employee>
<Name>$emp_name</Name>
<EmpId>$id</EmpId>
OUT

creating XML or Hash format
my $EmployeeDetail = {'Employee'=>[{'Name'=>{'content'=>$emp_name},{'EmpId'=>{'content'=>$id}}}]};

run shell or system command

  1.  my $ouptput = `ls`; #use backtick
  2.  my $output = system("command");


XML::Simple for xml 
reading 
my $xs = new XML::Simple(KeyAttr=>[]);
my $xml_data = $xs->XMLin("$xml_file");
if (ref $xml_data->{Employee} eq "HASH"){   #single elements
}
else{     # multiple elements

my $arr_ref = $xml_data->{Employee};
my $len = scalar @$arr_ref;      # find the length of array or elements
foreach my $employee (@$arr_ref)
{
if ($employee->{Designation} eq "Manager")
{
                      print " $employee->{Name}employee is Manager";
}
}
writing

#XMLout generate xml format output from hash or array list.      
my $xml_data = $xs->XMLout( $xml_employees,
                RootName => 'Employees',
                NoSort => 1,
                KeyAttr => []
                );
#now use file operation to write the $xml_data to file
print FILEHANDLE $xml_data

Data::Dumper
#This module is use for dumping variable hash array list on STDOUT for debug purpose.
Data::Dumper($xml_data);


a simple log routine for error or debug loging
sub log_msg
{
use POSIX qw/strftime/;
my( $file, $line )= ( caller )[1,2];
my $caller_sub = ( caller(2) )[3];
if (!defined ( $caller_sub))
{
$caller_sub = "main";
}
print STDERR "$file:$line:".strftime('%D %T',localtime).":$_[0]\n";
}

getting caller filename and line number
my( $file, $line )= ( caller )[1,2];
create directory
File::Path::mkpath($dir_path) ;
check file exist or not
if( -e $filename)  # file name with path
check is this file
if(-f $filename)
string match
if($text =~m/windows/) #text contain windows
if($text =~m/windows/i) #text contain windows ignore case
if($text =~s/windows/unix/) #text substitue windows with unix
how to do simple parsing and get the output in different variables like $1,$2 
my($text) = "/home/viru/mycodes/perlCode/first.pl";
if($text =~ m/(.*\/)(.*)$/)
{
my $directory = $1;
my $filename = $2;
                print "D=$directory, F=$filename\n";
}
create a daemon routine in perl
sub daemonize {
  use POSIX;
  POSIX::setsid or die "setsid: $!";
  my $pid = fork ();
  if ($pid < 0) {
print STDERR  "die main ";
     die "fork: $!";
  } elsif ($pid) {
print STDERR "exit pid : $pid";
     exit 0;
  }
  umask 0;

  foreach (0 .. (POSIX::sysconf (&POSIX::_SC_OPEN_MAX) || 1024))
     { POSIX::close $_ }
  open (STDIN, "</dev/null");
  open (STDOUT, ">/dev/null");
  open (STDERR, ">&STDOUT");
}


Referances :
O'Reilly's Programming Perl  http://www.troubleshooters.com/codecorn/littperl/perlreg.htm
Perl Regular Expressions http://docstore.mik.ua/orelly/perl/prog3/index.htm
   

No comments:

Post a Comment

would you like it. :)