Perl: Difference between revisions

From Halfface
Jump to navigation Jump to search
Line 88: Line 88:


regexp
regexp
. one key
. one key
^ beginning of line
^ beginning of line
$ end of line
$ end of line
/^[xfi]/ Starting with one x or f or i
/^[xfi]/ Starting with one x or f or i
/^[h-j]/ Starting with one h or i or j
/^[h-j]/ Starting with one h or i or j
() Deluttryck
() Deluttryck
quantifier how much a string matches.
quantifier how much a string matches.
? Noll eller en gång
? Noll eller en gång
a* a with 0 to unlimit a
a* a with 0 to unlimit a
a+ one or more a
a+ one or more a
{m} exackt m ggr
{m} exackt m ggr
{m,} minst m ggr
{m,} minst m ggr
{m,n} minst m max n ggr
{m,n} minst m max n ggr
=~ m|^abc| matchar abc i början
=~ m|^abc| matchar abc i början
.+? matchar så lite som möjligt
.+? matchar så lite som möjligt
modifierare
modifierare
/i/i matchar i case insensitiv
/i/i matchar i case insensitiv


$ skalär
$ skalär
@ lista
@ lista
% hash, associativa vektorer
% hash, associativa vektorer
$# maximun index in list
$# maximun index in list
$@ string that eval generates.
$@ string that eval generates.
\s remove space,tab,lf...
\s remove space,tab,lf...
\s+ godtyckligt
\s+ godtyckligt
\l Convert to lower case.
\l Convert to lower case.
$_ Default output input
$_ Default output input
$$ processid
$$ processid
$? exit status
$? exit status
@_ variable to send to subroutin
@_ variable to send to subroutin
@ARGV argument list. ('-v','-g','10','logfile')
@ARGV argument list. ('-v','-g','10','logfile')
$|=1; dont flush output stty
$|=1; dont flush output stty
$"=','; dubbelfnuttade listor
$"=','; dubbelfnuttade listor
_ fil operatorer och stat kan återänväda stat förfrågan.
_ fil operatorer och stat kan återänväda stat förfrågan.
$. Radräknare
$. Radräknare
$1 Delutryck som matchade
$1 Delutryck som matchade
local $/
local $/
@INC directories to find per modules, add directory export PERL5LIB=/bin:/hej
@INC directories to find per modules, add directory export PERL5LIB=/bin:/hej


&sub subrutin
&sub subrutin
$var2=\$var refere var2 to var
$var2=\$var refere var2 to var
@list('a',1,$a) add tree elements to list
@list('a',1,$a) add tree elements to list
@list([@odd]) add copy of list called anonymous list
@list([@odd]) add copy of list called anonymous list
$list[5] 6 possition in list
$list[5] 6 possition in list
@list = qw<Jan Feb>; Generate list
@list = qw<Jan Feb>; Generate list


$hash{'var'} element with index var in hash
$hash{'var'} element with index var in hash
%hash{'a'}='5'; add key a value 5
%hash{'a'}='5'; add key a value 5
if (exist($hash{a})){ run if key a exist i hash hash
if (exist($hash{a})){ run if key a exist i hash hash
delete($hash{'a'}); delete key a fron hash
delete($hash{'a'}); delete key a fron hash
split(' ',$str); split list output whith ' '
split(' ',$str); split list output whith ' '


my lexikal variabel, lokal variabel
my lexikal variabel, lokal variabel
$main::var main variabel
$main::var main variabel


styrstrukturer
styrstrukturer
Line 170: Line 170:


sträng list konverteringar
sträng list konverteringar
join (EXPR,LIST)
join (EXPR,LIST)
@words = ("merry", "go", "round");
@words = ("merry", "go", "round");
$str = join("-",@words);
$str = join("-",@words);


split (REGEXP,EXPR)
split (REGEXP,EXPR)
$str = "sys:x:3:3:sys:/dev:/bin/sh";
$str = "sys:x:3:3:sys:/dev:/bin/sh";
@fields = split (/:/, $str);
@fields = split (/:/, $str);
for $rad ( @fields ){
for $rad ( @fields ){
    print "$rad\n";
    print "$rad\n";
}
}


sub usage {
sub usage {
    print "use this command with optional -v"
    print "use this command with optional -v"
}
}


&subrutin(15,101,38) arguments are sent to a subroutin as a list
&subrutin(15,101,38) arguments are sent to a subroutin as a list


-command options.
-command options.
use Getopt::Long;
use Getopt::Long;
my %opts;
my %opts;
GetOptions(\%opts,'v','g=i') || &usage;
GetOptions(\%opts,'v','g=i') || &usage;
print "$opts{g}\n";
print "$opts{g}\n";


sub usage {
sub usage {
    print STDERR "Usage: option.pl [-v][-g n]";
    print STDERR "Usage: option.pl [-v][-g n]";
    exit 1;
    exit 1;
}
}


-globala symboltabellen
-globala symboltabellen
foreach my $var ( keys %main::){
foreach my $var ( keys %main::){
    print "$var\n";
    print "$var\n";


-formatting.
==formatting.==
my $rand1 = int(rand (90));
my $rand1 = int(rand (90));
my $rand2 = int(rand (10));
my $rand2 = int(rand (10));
my $rand3 = int(rand (50));
my $rand3 = int(rand (50));
printf ("%6d %6d %6d\n",$rand1,$rand2,$rand3);
printf ("%6d %6d %6d\n",$rand1,$rand2,$rand3);


-filehandlers
==filehandlers==
print "Who are you?\n";
print "Who are you?\n";
my $name = <STDIN>;
my $name = <STDIN>;
chomp($name);
chomp($name);
print "You are $name!!!\n";
print "You are $name!!!\n";


-print contents of file.
==print contents of file.==
my $file = "/tmp/test";
my $file = "/tmp/test";
open(IN,'<',$file) || die "open $file failed: $!";
open(IN,'<',$file) || die "open $file failed: $!";
# Loopa på rader i infilen.
# Loopa på rader i infilen.
while ( <IN> ) {
while ( <IN> ) {
    print $_;
    print $_;
}
}


-diamond operator @ARGV
==diamond operator @ARGV==
#!/usr/bin/perl
#!/usr/bin/perl
while (<>){
while (<>){
    print;
    print;
}
}


-list files
==list files==
opendir(DIR,"/etc");
opendir(DIR,"/etc");
my @files = sort grep(/x/,readdir(DIR));
my @files = sort grep(/x/,readdir(DIR));
closedir(DIR);
closedir(DIR);


-user external program
==user external program==
open(PING,'-|','/bin/ping -c 3 pizza');
open(PING,'-|','/bin/ping -c 3 pizza');
while (defined(my $ping = <PING>)){
while (defined(my $ping = <PING>)){
    print "$ping";
    print "$ping";
}
}
close PROG;
close PROG;


==Backslash magic==
==Backslash magic==

Revision as of 16:01, 2 June 2012

Reading

http://www.perl.org/books/beginning-perl/

Perl

Pathologically Eclectic Rubbish Lister

variables

the three types of variables in Perl are:

scalars = numbers, strings, or references    denoted $ 
arrays = sequentially-numbered lists of scalars     denoted @
hashes.= key-referenced lists of scalars     denoted %

operators

Operator                   Num     Str
  --------------------------------------
  Equal                      ==      eq
  Not equal                  !=      ne
  Less than                   <      lt
  Greater than                >      gt
  Less than or equal to      <=      le
  Greater than or equal to   >=      ge

man pages

perl      - overview               perlfaq   - frequently asked questions
perltoc   - doc TOC                perldata  - data structures
perlsyn   - syntax                 perlop    - operators and precedence
perlrun   - execution              perlfunc  - builtin functions
perltrap  - traps for the unwary   perlstyle - style guide

"perldoc" and "perldoc -f"

cpan

Comprehensive perl archive network

Perl kurs

Christer Ekholm
First two letters and first letter of last name@init.se
TIMTOWTDI (There Is More Than One Way To Do It)

regexp		regular expression . a* a? ^a a$,perls RE för andra.
semantik	meaning that is expressed in a language and words
notation	ways to represent a matimatic equation
analogi		motsvarighet, nagot svart beskrivs enkelt
iteration	upprepning
deklarera	förklara
definera	definera subrutiner
context		sammanhang
explicit	uttryckligen
implicit	underförstått
logiska operatorer	and,or,not,||,&&,!
aritmetisk	+-/*
bitoperatorer	AND,OR,XOR,leftand right shift.
re		reguljära utryck, mönsterpassning.
relation operatorer	numeriska	sträng
			==	!=	eq 	ne
<	>	lt	gt
<=	>=	le	ge
jämförelse operatörer	numeriska	sträng
 			<=>		cmp
citatecken	"" variabler expanderar qq,  variabler oförändrade q, `` exekveras qx

How to get information

perldoc -f variabler	Show help page for variables
perldoc -f -X		Show file handle test.
perldoc perlform	Format information
perldoc Getopt::Long	Show help for Getopt
perldoc -q		Letar i perl faq
perldoc perlmodlib	Lista inbyggda moduler
perldoc perlpod

Debug

emacs M-x perldb	Debugga perl i emacs
perl -d:ptkdb /scrpt	Debugga perl  

Perl code

use strict;	explesist namnge package variable
use warning;	show warning messages
perl -w		show warning messages
use Getopt::Long:	Use getoptions module

package mypkg; change package

Perl Oneliners:

perl -ne 'print if /a/'			Grep all lines containing a. (-n create a loop) (-e, allows you to define Perl code to be executed by the compiler)
perl -e 'print join("\n",@INC),"\n"'	Var söker perl efter moduler
perl -c kod.pl				Kontrollera koden.

regexp

.		one key
^		beginning of line
$		end of line
/^[xfi]/	Starting with one x or f or i
/^[h-j]/	Starting with one h or i or j
()		Deluttryck
quantifier	how much a string matches.
?		Noll eller en gång
a*		a with 0 to unlimit a
a+		one or more a
{m}		exackt m ggr
{m,}		minst m ggr
{m,n}		minst m max n ggr
=~ m|^abc|	matchar abc i början
.+?		matchar så lite som möjligt
modifierare	
/i/i		matchar i case insensitiv
$		skalär
@		lista
%		hash, associativa vektorer
$#		maximun index in list
$@		string that eval generates.
\s		remove space,tab,lf...
\s+		godtyckligt
\l		Convert to lower case.
$_		Default output input
$$		processid
$?		exit status
@_		variable to send to subroutin
@ARGV		argument list. ('-v','-g','10','logfile')
$|=1;		dont flush output stty
$"=',';		dubbelfnuttade listor
_		fil operatorer och stat kan återänväda stat förfrågan.
$.		Radräknare
$1		Delutryck som matchade
local $/	
@INC		directories to find per modules, add directory export PERL5LIB=/bin:/hej
&sub		subrutin
$var2=\$var	refere var2 to var
@list('a',1,$a)	add tree elements to list
@list([@odd])	add copy of list called anonymous list
$list[5]	6 possition in list
@list = qw<Jan Feb>;	Generate list
$hash{'var'}	element with index var in hash
%hash{'a'}='5';	add key a value 5
if (exist($hash{a})){	run if key a exist i hash hash
delete($hash{'a'});	delete key a fron hash
split(' ',$str);	split list output whith ' '
my		lexikal variabel, lokal variabel
$main::var	main variabel

styrstrukturer

-iterationer
while [EXPR] BLOCK
until [EXPR] BLOCK
do BLOCK while [EXPR]
do BLOCK until [EXPR]
for VAR (EXPR) BLOCK
for (EXPR1; EXPR2; EXPR3) BLOCK
-selection
if (EXPR) BLOCK
if (EXPR) BLOCK1 elsif (EXPR2) BLOCK2... elxe BLOCKn
unless (EXPR) BLOCK

filehandels

STDIN,STDOUT,STDERR

Regular Expression.

a.b		a any key b
^a.c$		starting with a any key end with c
X1*		X1 folles by 0 to many 1
^[]abc]		strings starting with any of ]abc
[^zxy]		Does not have any of zxy in possition
a{8}		aaaaaaaa
uttr{m,n}	uttr förekommer mellan m och n gånger
^ *$		empty line or only blanks

sträng list konverteringar

join (EXPR,LIST)
@words = ("merry", "go", "round");
$str = join("-",@words);
split (REGEXP,EXPR)
$str = "sys:x:3:3:sys:/dev:/bin/sh";
@fields = split (/:/, $str);
for $rad ( @fields ){
    print "$rad\n";
}
sub usage {
    print "use this command with optional -v"
}
&subrutin(15,101,38)	arguments are sent to a subroutin as a list

-command options.

use Getopt::Long;
my %opts;
GetOptions(\%opts,'v','g=i') || &usage;
print "$opts{g}\n";
sub usage {
    print STDERR "Usage: option.pl [-v][-g n]";
    exit 1;
}

-globala symboltabellen

foreach my $var ( keys %main::){
    print "$var\n";

formatting.

my $rand1 = int(rand (90));
my $rand2 = int(rand (10));
my $rand3 = int(rand (50));
printf ("%6d %6d %6d\n",$rand1,$rand2,$rand3);

filehandlers

print "Who are you?\n";
my $name = <STDIN>;
chomp($name);
print "You are $name!!!\n";

print contents of file.

my $file = "/tmp/test";
open(IN,'<',$file) || die "open $file failed: $!";
# Loopa på rader i infilen.
while ( <IN> ) {
    print $_;
}

diamond operator @ARGV

#!/usr/bin/perl
while (<>){
    print;
}

list files

opendir(DIR,"/etc");
my @files = sort grep(/x/,readdir(DIR));
closedir(DIR);

user external program

open(PING,'-|','/bin/ping -c 3 pizza');
while (defined(my $ping = <PING>)){
    print "$ping";
}
close PROG;

Backslash magic

\t          tab                   (HT, TAB)
\n          newline               (LF, NL)
\r          return                (CR)
\f          form feed             (FF)
\a          alarm (bell)          (BEL)
\e          escape (think troff)  (ESC)
\033        octal char (think of a PDP-11)
\x1B        hex char
\c[         control char
\l          lowercase next char (think vi)
\u          uppercase next char (think vi)
\L          lowercase till \E (think vi)
\U          uppercase till \E (think vi)
\E          end case modification (think vi)
\Q          quote (disable) pattern metacharacters till \E

\w  Match a "word" character (alphanumeric plus "_")
\W  Match a non-word character
\s  Match a whitespace character
\S  Match a non-whitespace character
\d  Match a digit character
\D  Match a non-digit character