|
home /
infca /
perl
(navigation links)
|
Lo consiguieron porque no sabian que era imposible
|
Intro
Perl
Install from
homepage
To display PERL version, use:
c:\> perl -v
This is perl, v5.8.8 built for msys
Copyright 1987-2006, Larry Wall
Hello :
#!/usr/opt/perl5/bin/perl
#
# Program to do the obvious
#
print 'Hello world.'; # Print a message
You can always run the program with warnings using the command
perl -w progname
at the prompt.
This will display warnings and other (hopefully) helpful messages before it tries to execute the program.
To run the program with a debugger use the command
perl -d progname
The most basic kind of variable in Perl is the scalar variable.
Scalar variables hold both strings and numbers,
and are remarkable in that strings and numbers are completely interchangable.
$priority = 9;
$priority = 'high';
Perl is case sensitive, so $a and $A are different.
A slightly more interesting kind of variable is the array variable
which is a list of scalars (ie numbers and strings).
Array variables have the same format as scalar variables except that they are prefixed by an @ symbol.
The statement
@food = ("apples", "pears", "eels");
@music = ("whistle", "flute");
assigns a three element list to the array variable @food
and a two element list to the array variable @music.
The array is accessed by using indices starting from 0,
and square brackets are used to specify the index.
The expression
$food[2]
returns
eels. Notice that the @ has changed to a $ because
eels is a scalar.
It is also possible to assign an array to a scalar variable. As usual context is important. The line
$f = @food;
assigns the length of @food, but
$f = "@food";
turns the list into a string with a space between each element.
This space can be replaced by any other string by changing the value of the special
$" variable.
File handling :
#!/usr/local/bin/perl
# Program to open the password file, read it in, print it, and close it again.
$file = '/etc/passwd'; # Name the file
open(INFO, $file); # Open the file
@lines = <INFO>; # Read it into an array
close(INFO); # Close the file
print @lines; # Print the array
Using shell :
here
See
Cron sample.
Exec vs System vs Open
Exec (no return) versus System (returns).
Use Open if you want to pipe the command (as input or output) to your script
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;
}
url
Sample :
#!/usr/bin/perl
#
# print "Print time() in SysLog.\n" ;
($seg, $min, $hora, $dia, $mes, $anho, @zape) = localtime(time) ;
# Use four digit year ($year is a value based on # of years since 1900)
$anho += 1900;
# Set to 2 digit month from 01 to 12
$mes = $mes + 1 ;
if(length($mes) == 1) {
$mes = "0" . $mes;
}
# Set to 2 digit day
if(length($dia) == 1) {
$dia = "0" . $dia;
}
if(length($hora) == 1) {
$hora = "0" . $hora;
}
if(length($min) == 1) {
$min = "0" . $min;
}
if(length($seg) == 1) {
$seg = "0" . $seg;
}
$madata = "SAGcron15min - son les $hora:$min del $dia/$mes/$anho." ;
$linia = "logger -p user.info $madata" ;
system($linia) ;
$file = "/home/sebas/scripts/cron/newLog.txt";
if (unlink($file) == 0) {
# print "+++ File deleted successfully.\n";
} else {
# print "--- File was not deleted.\n";
}
system("ps -ef | grep vmx >> $file") ;
$linia = "logger -p user.info -f $file" ;
system($linia) ;
How to read a file in Perl
#!/usr/local/bin/perl
$fname = "data.txt" ;
open (MYFILE, $fname) || die "Could not open $fname\n" ;
while (<MYFILE>) {
chomp; ## removes the last character from a string, so removes the trailing "\n"
print "$_\n"; ## print default
input
}
close (MYFILE);
url,
log scan
How to verify you are root
#!/usr/bin/perl
use strict;
use warnings;
print "*** Who Am I ?\n" ;
my $login = (getpwuid $>) ;
print "*** You are ($login).\n" ;
die "--- must run as root\n" if $login ne 'root' ;
execute a remote command
#!/usr/bin/perl
print "*** 1 - go there and run a command.\n" ;
system ( " ssh myrmthost '/var/tmp/rmt/putdate.sh' " ) ;
How to write a file in Perl
#!/usr/local/bin/perl
open (MYFILE, '>>data.txt');
print MYFILE "Bob\n";
close (MYFILE);
url
Another :
#!/usr/local/bin/perl
# somewhere earlier in the code I define my filename ...
my $outfile = 'footer.html';
# open the file, saying i want to write to it with the '>>' symbol
open (FILE, ">> $outfile") || die "problem opening $outfile\n";
# print a plain text line to the file
print FILE "<div align=\"center\">\n\n";
# write an array of lines to the file here
print FILE @lines1;
# print another plain text line to the file
print FILE " \n\n";
# write a second array of lines to the file
print FILE @lines2;
# print a closing div tag to the file
print FILE "</div>\n";
# close the file when there's nothing else to write to it
close(FILE);
url
How to delete a file or a (non empty) directory
#!/usr/bin/perl
## unlink : http://www.tizag.com/perlT/perldelete.php
## delete non empty directories : http://www.caveofprogramming.com/guest-articles/perl/perl-file-delete-deleting-files-and-directories-in-perl/
## concatenate : http://www.perlmonks.org/?node_id=32418
use File::Path; # required by rmtree
print "content-type: text/html \n\n"; #The header
$fn1 = "newtext.txt";
print "Lets UNLINK ($fn1).\n";
my $removed = unlink($fn1) or die "Could not delete the file!\n";
print "Removed $removed file(s).\n";
if ( $removed > 0 ) {
print "File ($fn1) deleted successfully.\n";
} else {
print "File ($fn1) was not deleted.\n";
}
$fn2 = "mytext.txt";
my $command = "del " . $fn2 ;
print "Lets execute comand ($command).\n";
`$command`;
my $dir = "temp";
rmtree $dir;
if( -e $dir )
{
print "Directory '$dir' still exists";
}
else
{
print "Directory '$dir' deleted.";
}
exit 0;
How to scan all lines of a file
#!/usr/bin/perl
## http://perlmeme.org/howtos/perlfunc/split_function.html
## http://perlmaven.com/trim
## or
## use String::Util qw(trim);
sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
use strict;
use warnings;
my $data = 'Bob the Builder <<< fn ';
my @values = split('<<<', $data);
my $num = 0 ;
my $z = "";
foreach my $val (@values) {
$num = $num + 1 ;
print "($num)aaa${val}aaa\n";
$z = trim( $val ) ;
printf "net <%s>\n", $z ;
}
exit 0;
This code produces this result :
c:\Sebas\perl>perl split.pl
(1)aaaBob the Builder aaa
net <Bob the Builder>
(2)aaa fn aaa
net <fn>
How to kill a thread
Threads
kill,
kill.
Use SIGINT to reload configuration
perldoc
Updating your installation
c:\> perl -MCPAN -e'install "LWP::Simple"'
CPAN: Storable loaded ok
Going to read /.cpan/Metadata
Database was generated on Thu, 14 Aug 2014 16:17:02 GMT
Running install for module LWP::Simple
Running make for M/MS/MSCHILLI/libwww-perl-6.08.tar.gz
CPAN: Digest::MD5 loaded ok
Checksum for /.cpan/sources/authors/id/M/MS/MSCHILLI/libwww-perl-6.08.tar.gz ok
gzip: stdout: Invalid argument
Scanning cache /.cpan/build for sizes
libwww-perl-6.08/
libwww-perl-6.08/talk-to-ourself
. . .
Using LWP instead of WGET
use strict;
use warnings;
use LWP::Simple;
sub main
{
my $data = get("http://news.bbc.co.uk");
print "Retrieved " . length($data) . " bytes of data.";
}
main();
Documentacio on-site
If you know a module's name, you can get documentation on it by typing
perldoc Net ::POP3
Ugly
I dont like this :
You are missing the dot (.) before the asterisk. It should be:
if(/^([\d]+).*(hullBts_static)/)
Neither this :
sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
This is worse:
Global symbol "$linia" requires explicit package name at ./feina.pl line 49.
Global symbol "$linia" requires explicit package name at ./feina.pl line 49.
FALTA ";" AL FINAL DE LA LINIA o FALTA DECLARAR LA VARIABLE (my) !!!