Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

$< real UID

Perl Cheat Sheet: a handy reference $> effective UID


NOTES:
for ⇔ foreach ALWAYS
Regex Charclasses
. ⇔ [^\n] anything
$( real GID conditions and loops could use last, next, redo \s ⇔ [\x20\f\t\r\n] white spaces
Getting Help:
$) effective GID followed by optional label \w ⇔ [A-Za-z0-9_] word (alphanum_)
pelrdoc perl
$& string being matched a condition or a loop could have a label, so use it \d ⇔ [0-9] digit
pelrdoc perlSOMETHING
$` the preceding str conditions could be used after a single statement like \S \W \D negate \s \w \d non-...etc.
perldoc perlfaq
$' the following str print "Ok" if ($ok); PerlDoc:perlrequick, perlretut,perlre, perlreref
perldoc perlfaqN where N is 1..9
$ARGV filename of <> PerlDoc: perlsyn
perldoc -f FUNC Regex Metachars:
@ARGV command line args NUMBERS vs STRINGS ^ string begin
Running Perl %ENV environment = =
-e CMD single line of script $ str. end(before \n)
@_ args in subs + .
-w warnings on + one or more
@INC include paths == != eq ne
-c checks syntax only * zero or more
$~ format (perldoc perlform) < > <= >= lt gt le ge
-n non-printing input loop ? zero or one
$^ top-of-page format name <=> cmp
-p printing input loop {3,7} repeated in range 3-7 times
$^A formline accumulator
-i [EXT] in-place edit, EXT of backup
String literals: [ ] character class, set memeber
$^L output formfeed (\f)
Name is week? Method 1 Method 2 | alternation
-a auto split (Splits to @F) $^T script run time (epoch)
Literal ' ' q{ } \b word boundary
-F REGEXP auto split delimiter $^X interpreter filename
Literal yes " " qq{ } \z string end
-0 [OCT|HEX] set input record sep '$/' $! errno or errstr
Command yes ` ` qx{ } () capture
-00 paragraph record mode $@ eval error msg
Word list qw{ } (?: ) no capture
-M MOD load a module $? return value child proc
Pattern match yes / / m{ } (?= ) +ve ahead assertion
-I [DIR] perpend DIR to @INC. $. line number (last read)
compile pat yes qr{ } (?! ) -ve ahead assertion
-S use PATH for exec $% page # of output channel
Substitution yes s/ / / s{ }{ } (?<=) +ve back assertion
-l [OCT] auto-chomp and set '$\' $= lines in output channel page (default 60)
Trans tr{ }{ } (?M ) Emb.REGEX MODIFIERS
-CSD enable UTF-8 $- lines remaining on page
here-doc yes <<EOS UTF8 I/O:
-T taint checking (perldoc perlsec) $| autoflush (write)
NOTE: you can replace {} with any non-alphanum delimiter like = or + #! /usr/bin/perl
-d enable debugger. "perl -de 0" $ARGV filename of <> NOTE: week works if delimiter is not ' ', interpolation is done with week, use utf8;
-D NUM sets debugging flags $0 script filename NOTE: $n="123"; ⇔ $n=123; and $a="ok" ⇔ $a=v111.107
-u dump core, see undump(1) $+ last sub-pattern use encoding 'utf8';
NOTE: binary operators with strings, eg. print "wxyz" ^ " ","\n";
-U unsafe operations mode $1 .. $9 .. ${100}.. sub-patterns use open ':utf8'; # input and output default layer will be UTF-8
PerlDoc: perlop
-v ver and patchlevel of script $^I in-place edit #...
-x [DIR] seek script after "#!" in input Escape Specials: PerlDoc:perlunicode
NOTE: "undef $^I" to turn off
\t TAB
-s -xyz=abc cause $xyz='abc' PerlDoc: perlvar Some Important Modules:
EXAMPLE: perl -s -e 'print "$myvar\n"' -- -myvar="myval" \n newline
Operator Precedence CGI, DBI (databases like MySQL), Digest::MD5this,
PerlDoc: perlrun \r return Encode, File::Basename, Getopt::Long, Gtk,
-> \f form feed Locale::gettext, Math::BigFloat, Math::BigInt,
Contexts: void scaler list
++ -- \b backspace Math::BigInt::Calc, Math::BigInt::CalcEmu,
SIGILS: $scalar @array %hash &sub *glob
** \a alert (beep) Math::BigRat, Math::Complex, Math::Trig, Net:Ping,
Scalers: number string reference glob undef Net::SMTP, O (compiler backend), ops, overload, POSIX,
! ~ \ u+ u- \e escape
Arrays Hashes Safe, SDL, Tk, Unicode::Normalize, XML:Parser
=~ !~ \l lower next
Whole: @array %hash Perl One-Liner: Copyright © 2002, Ben Okopnik. Linux Gazette
* / % x \u upper next
Slice: @array[0, 2] @hash{'a', 'b'} perl -wlne '/title>([^<]+)/i&&rename$ARGV,"$1.html"' *
+ - . \L lower till \E
Element: $array[0] $hash{'a'} to raname html files according to their titles
<< >> \W upper till \E
$#array last index
named uops perl -ne 'END{print "@a\n"}push @a,/(\w+\@\w+\.\w+)/g'
@a=1..3 ⇔ @a=(1,2,3) @b=A..C ⇔ @b=("A","B","C") \Q quote till \E
< > <= >= lt gt le ge silly spambot, to get emails from STDIN (or followed files )
@a=keys%hash @a=values%hash \E end \L \W or \Q
$$foo[1] ⇔ $foo->[1]
== != <=> eq ne cmp \xHEX \0OCT \x{} \N{} Recommendations:
& EXAMPLE: $a="err"; print"\U$a\E\n"; DO:
$$foo{bar} ⇔ $foo->{bar}
| ^ use strict; use warnings;
${$$foo[1]}[2] ⇔ $foo->[1]->[2] ⇔ $foo->[1][2] Numerical Literals
&& use Modules; # Do not reinvent the wheel
References decimal 1234
|| my $var; # declare locale variable scope
\ reference binary 0b1100101
.. ... open(..) or die $!; # expect errors
$@%&* dereference octal 01234
?: DO NOT:
[ ] anon. arrayref hexadecimal 0xDEADbeef
= += -= *= etc. "$foo"
{ } anon. hashref exponential 2.998e+8
, => $$variable_name
\( ) list of refs legibility 299_792_458
list ops `$userinput` # execute arbitrary string from user/client
PerlDoc: perlreftut, perlref, perldsc, perllol,perldata not NOTE: underscore _ is ignored
/$userinput/ # compile arbitrary RE from user/client
PerlDoc: perlnumber
Special Varialbles and die "Can’t open: $!" unless open(FOO,$foo); # not readable
$_ default variable or xor
Regex Modifiers: PerlDoc: perlstyle
$/ input record sep. (\n) /i case insens.
PerlDoc: perlop
/m line based ^$
Web Sites:
$\ output record sep. SYNTAX perl.com perlmonks.org perl.apache.org perl.plover.com
$, output field sep. /s case . to include \n
LABEL: # a label for a loop/condition tpj.com pm.org cpan.org search.cpan.org
$" sep. for "@ARRAY" /x ign. wh.space
for (LIST) { } # set $_ to current LIST member perldoc.com use.perl.org parrotcode.org
$: (eg. \s and hyphens) /g global
for (a;b;c) { }
/o evaluate vars only once JAPH: Just Another Perl Hacker
$; multiD. array emu(\034) while ( ) { } until ( ) { }
/e evaluate replacement perl -e 'printf "U R %x man.\n", 57005;'
$] perl version str. if ( ) { } elsif ( ) { } else { } perl -e '$s=sprintf "%x\n", 3735928559; $s=~s/db/d b/; print $s'
$0 script filename unless( ) { } elsif ( ) { } else { }
$$ PID
By Muayyad Saleh Al-Sadi <alsadi@gmail.com>
goto LABEL
Built-in Functions (underlined defaults to $_) Array and List Functions I/O Operations wait waits for a child process to terminate
delete $H{K} Delete value from hash. FH is a file handle that is created with open (or waitpid PID, FLAGS
Conversion
each %H Return next (key,val) array or null predefined like STDOUT) like wait but for PID
abs X absolute value
exists $H{K} Check if hash key exists. <> reads from file passed with @ARGV (STDIN elsewhere) times Returns a 4-element array
int X str to integer
keys %H Return an array of hash keys <FH> reads a line (or array of all lines) (0: $user, 1: $system, 2: $cuser, 3: $csystem)
hex X hex to dec
values %H Return an array of hash values NOTE: FH is recommended to be in upper case umask [EXPR] sets the umask for the process
oct X oct to dec
scalar %H true if H has elements defined NOTE: use or die “could not ...\n$!” getpwnam NAME get user information by login name
chr X num(ASCII) to str
scalar @A Return number of A elements open FH, M, FN [,L] getpwuid UID same but by UID
ord X first char to num(ASCII)
reverse L invert order of L there are many more see perldoc -f open returns array (0:$name, 1:$passwd, 2:$uid, 3:$gid,
Arithmetics M: 'r', 'r+', 'w', 'w+', 'a', and 'a+' 4:$quota, 5:$comment, 6:$gcos, 7:$dir, 8:$shell)
unshift @A, L
sin X getgrnam NAME get group information by group name.
M: '>','>>','<' and all with '+' (eg. 'a+' '+>>')
Prepends L to A, and returns the number of elements in the new array.
cos X
shift [@A] return first element and remove it M: '-|', '|-' create pipe, L arguments for FN command getgrgid GID same but by group GID.
atan2 Y,X arctan of Y/X
pop @A Pop off and returns last value of A PerlDoc: perlipc returns array (0:$name, 1:$passwd, 2:$gid, 3:$members)
sqrt X square root of X
push @A, L Push values of L onto the end of A binmode FH set to binary mode (useless on UNIX) Network Information:
exp X e to the power X
join E, L close FH
return strings of L joined by E separator closes file or pipe FH gethostbyaddr, gethostbyname, getnetbyaddr,
log X log X base e
map E, L or map {BLOCK} L eof FH true if the all reading is done getnetbyname, getservbyname, getservbyport,
Binary Manipulations eof
Evaluate E or BLOCK for each element of L, locally setting $_ to it. Modifying EOF status for the last file read. getprotobyname, getprotobynumber,..etc
vec X, O, B get B bits at O offset of X fcntl FH,N,$V
$_ will modify the corresponding element from L. Returns the list of results. UNIX fcntl, see man fcntl(2)
pack T, LS list to binary struct grep E,L or grep {BLOCK} L fileno FH Returns the file descriptor EXAMPLE: list network services, protocols and ports
unpack T, X struct to list flock FH, OP
set $_ for each L element, allow modification,returns array where E true. file lock like UNIX flock(2), where perl -e 'while (($s,$a,$p,$P)=getservent) {print
Time and Random Gen. splice @A, O [ , N [ , L ] ] OP: 1 shared, 2 exclusive, 4 non-blocking, or 8 unlock "$s\t$P:$p\n"}'
rand [X] 0≤rand(X)<X getc [FH]
Removes the N elements of @A designated by offset O, replacing them with L, read character(or empty string) Networking and IPC
srand [X] seed (not needed) Returns the elements removed. ioctl FH,N,$V UNIX ioctl(2) accept, bind, connect, getpeername, getsockname,
time seconds since epoch sort [FUNC] L pipe FH_R, FH_W create a pair of connected pipes getsockopt, recv, send, setsockopt, shutdown, socket
gmtime X time to array return sorted version of L, FUNC receives $a $b sprintf F,L return string of formatting L as F socketpair, msgctl,msgget, msgsnd, msgrcv, semctl,
EXAMPLE: @L = sort {$a cmp $b} @str_array; print [FH][L] output to FH semget, semop, shmctl, shmget, shmread, shmwrite, ...
localtime X time to array
EXAMPLE: ($sec, $min, $hour,$mday, $mon, split [PAT [ , E [ , M ] ] ] printf[FH][L] output to FH
$year,$wday,$yday,$isdst) = localtime(time); Splits a string E into an array of strings, and returns it. syswrite FH,SCALER,L[,O] output to FH By Muayyad Saleh Al-Sadi <alsadi@gmail.com>
String Manipulations at most M element are get, If no PAT splits at the whitespace. read FH,$V,L[,O]
chomp L del ending "\n" from each L sysread FH,$V,L[,O]
If not in array context, returns number of fields and splits to @_.
based on perlcheat
chop L del each last char from L File unary tests input $V from FH, L: length,O: offset by Juerd Waalboer<juerd@cpan.org>
length E num characters in E seek FH,P,W set offset, W: 0 abs,1 cur, 2 EOF
-r -w -x is file readable/writable/executable
http://juerd.nl/site.plp/perlcheat
lc E return lowercase E -R -W -X for real UID/GID not the effective one $nfound=select $RV, $WV, $EV,TIMEOUT
lcfirst E same with 1st char only -o -O is file owned by effective/real uid. like UNIX select(2),all can be undef, set vectors with and Perl 5 Desktop Reference
$RV=''; vec($RV,fileno(FH),1) = 1;
uc E return uppercased E -e -z File exists/has zero size. by Johan Vromans
ucfirst E same with 1st char only -s return size (ie. exists and non-empty) tell [FH] current file position
quotemeta E return E with special RE quoted -f -d is file regular file/a directory. Formatted Output Suggested References: Perl 5 Pocket Reference
crypt S,SALT Encrypts a string -l -S -p is symbolic link/a socket/FIFO pipe formline PIC,L Formats L according to PIC, add to $^A
eval E run perl expression -b -c is file a block/character device write [FH] writes a formatted record to FH
index S,SUB[,O] find 1st occurrence of SUBSTR in S -u -g -k has setuid/setgid/sticky bit set. to set the format use
rindex S,SUB[,O] same but last -t if filehandle (default STDIN) a tty. format[FH] =
substr E,O[,L] get L chars after O from E -M -A -C modification/access/inode-change time(days) FORMLIST
Search and Replace Functions -T -B is text/non-text (binary) file. .
pos S \G position m//g (May be assigned to.) NOTE: both -T and -B return true on a null file (or a PerlDoc: perlform
study[$V] study $V to speed next matching on it file at EOF when testing a filehandle) see $-, $^, $~, $^A, $^F, $- and $=
[E=~][m]/RE/[g][i][m][o][s][x] File Operations System interaction
Search E for a RE. first m is to use different pair of delimiters. chmod MODE,L set permissions of a list of files alarm SEC send SIGALRM after SEC seconds.
return array of subexpressions parentheses chown U,G,L owner and group of a list of files chdir [E] Changes the working directory.
[$V=~]s/RE/STR/[e][g][i][m][o][s][x] truncate F, S set size of F to S. filename or handle chroot DIR for process and its children.
Replace all non-overlapping matches of RE with STR link ORIG, LINK make a hard link die [L] Prints L to STDERR
return number of replacements. symlink ORG,LINK make a soft link warn [L] like die, but doesn't exit
RE Modifiers: mkdir DIR, MODE Creates a directory exec L system command in L; does not return
g global match (more than once) readlink E Returns the value of a symbolic link exit [E] Exits immediately
i case-insensitive rename OLD, NEW Changes the name of a file, or move it fork UNIX fork(2), used to in IPC
s single line string rmdir FILENAME Deletes the directory if it is empty getlogin current login name
m multi-line string (^ $ differ) unlink L Deletes a list of filenames getpgrp [PID] group for process PID (or current)
o opt. interpolates variables once utime A,M,L set access and modification times setpgrp PID, PGRP
x enable extensions lstat F like stat, but does not follow link getppid parent PID
e replacement is to be evaluated as exp stat F Returns a 13-element array getpriority WHICH, WHO
[$VAR=~]y/SET1/SET2/[c][d][s] (0: $dev, 1: $ino, 2: $mode, 3: $nlink, 4: $uid, setpriority WHICH, WHO, PRIORITY
[$VAR=~]tr/SET1/SET2/[c][d][s] 5: $gid, 6: $rdev, 7: $size, 8: $atime, 9: $mtime, see UNIX getpriority(2)
Translates SET1 characters to corresponding SET2 10: $ctime, 11: $blksize, 12: $blocks) glob PAT shell pattern matching, return array
characters, return number of characters replaced. Directory Listing kill SIG,L Sends a signal to a list of PIDs
Modifiers: c complements SET1; s squeezes repetitions opendir DH,DIR close it with closedir DH sleep [SEC]
d del. chars having no corresponding chars in SET2; readdir DH Returns the next entry syscall L
NOTE: in array context return an array of entries system L like exec L with a fork, and wait

You might also like