Perl

From Halfface
Jump to navigation Jump to search

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)

Dictionary

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 mathematical 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.

regex

.		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
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

Special meaning

$		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

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