You are on page 1of 1

Network Programming with Perl Cheat Sheet Series

Perl Help Command-line Arguments Variables Relevant Perl Functions


Install Package $ sudo apt-get install perl-doc -0[octal/hexadeci Specifies the input record separator ($/ ) as an octal or hexadecimal $var Default variable abs Absolute value
perldoc perldoc Look up Perl documentation in Pod format mal] number 21st element of array @var
$var[20] accept Accept an incoming socket connection
perldoc perltoc Perl documentation Table of Contents (ToC) -a Turns on autosplit mode when used with a -n or -p $p = \@var Now $p is a reference to @var bind Binds an address to a socket
perldoc perl Basics language interpreter
Causes Perl to check the syntax of the program and then exit 21st element of array referenced by $p
perldoc perlfunc List of built-in Perl functions -c $$p[20] binmode Prepare binary files for input/output
without executing it
perldoc -f <function_name> Help with a specific function $var[-1] Last element of array @var chdir Change current working directory
-C [number/list] The -C flag controls some of the Perl Unicode features.
perldoc perlop List of Perl operators and precedence $var[$x][$y] $y-th element of $x-th element of array @var chmod Changes the permissions on a file/list of files
-d, -dt Runs the program under the Perl debugger
perldoc perlmodlib For constructing perl modules and finding existing ones $var{’JAN’} A value from ‘hash’ %var
-Dletters, chop Remove the last character from a string
perldoc perllocal Locally installed modules list (if any) Sets debugging flags (only if your perl binary has been built with
-Dnumber debugging enabled) $p = \%var Now $p is a reference to hash %var chown Change the ownership of the file
perldoc <module_name> Documentation for specific module
-e commandline May be used to enter one line of program $$p{’JAN’} A value from hash referenced by $p close Close file
Comparison operators Like -e, except it implicitly enables all optional features (in the main $#var Last index of array @var closedir Close directory
-E commandline
Arithmetic Strings compilation unit)
@var The entire array connect Connect to a remote socket
Less than < lt -f Disable executing $Config{sitelib}/sitecustomize.pl at startup
@var[5,6,7] A slice of array @var crypt One-way encryption
Greater than > gt -F pattern Specifies the pattern to split on for -a (regex // , "" , or '')
@var{’X’,’Y’} A slice of %var; same as ($var{’X’},$var{’Y’}) delete Deletes a value from a hash
Less than or equal <= le -h Prints summary if the options
%var The entire hash; die Raise an exception
Greater than or equal >= ge -m -mmodule executes use module (); before executing your program
$var{’a’,1,...} Emulates a multidimensional array; dump Create a core dump immediately
Equality == eq -M -Mmodule executes use module ; before executing your program
eof End of file
Inequality != ne -n Input loop in the script without line printing Socket Programming
eval Compile and run code
Boolean operators -p Input loop in the script with line printing Server-side Method
exit Terminate running s program
Makes Perl use the PATH environment variable to search for the socket() call- socket( SOCKET, DOMAIN, TYPE, PROTOCOL );
Description Example -S program exp
bind() call -bind( SOCKET, ADDRESS ); Exponential
C-style Logical AND
&& ($a && $b) is false -T Turns on taint so you can test listen() call- listen( SOCKET, QUEUESIZE ); fork Create a new process just like the existing one
operator
Prints the version and patchlevel of your perl executable
accept() call - accept( NEW_SOCKET, SOCKET );
Logical AND operator and ($a and $b) is false
-v gethostbyaddr Get host record IP address
Prints summary of the major perl configuration values and the Server-side Socket Script Example
C-style Logical OR -V gethostbyname Get host record given name
|| ($a || $b) is true current values of @INC #!/usr/bin/perl -w
operator
# Filename : serversocket.pl getlogin Return who is logged in at this TTY
-w Prints warnings about dubious constructs
Logical OR operator or ($a or $b) is true
Tells Perl that the program is embedded in a larger chunk of getnetbyname Get networks record given name
C-style Logical NOT -xdirectory use strict;
! !($a) is false unrelated text getnetent Get next networks record
operator use Socket;
Logical NOT operator not not($a) is false Special Variables getpeername FInd the other end of a socket connection
# use port 7999 getprotobyname Get protocol record given name
$ Default variable
my $port = shift || 7999;
Quotes ($foo = 5;) $/ The input record separator, newline by default my $proto = getprotobyname('tcp');
getprotobynumber Get protocol record numeric protocol

Single-quotes - Literal
$\ The output record separator for the print operator
my $server = "localhost"; # Host IP running the server getprotoent Get next protocols record
$bar = 'it is worth $foo'; it is worth $foo
data enclosing
$( The real GID (Group ID) of this process
getpwent Get next passwd record
Double-quotes - # create a socket
Interpolated data $bar = "it is worth $foo"; it is worth 5 $) The effective GID (Group ID) of this process socket(SOCKET, PF_INET, SOCK_STREAM, $proto) getpwnam Get passwd record given user login name
enclosing or die "cannot open socket $!\n"; getpwuid
$& The string matched by the last successful pattern match Get passwd record given user ID
$bar = "it is \"worth\" $foo"; it is "worth" 5 setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)
Escape characters The string preceding whatever was matched by the last getservbyname Get services record given its name
$bar = 'it is \'worth\' $foo'; it is 'worth' $foo $` or die "cannot make reusable $!\n";
successful pattern match getservbyport
$bar = q(it is 'worth' $foo); it is 'worth' $foo Get services record given numeric port
Without quotes The string following whatever was matched by the last
$bar = qq(it is "worth" $foo); it is "worth" 5 $' # bind to a port followed by listne getservent Get next services record
successful pattern match
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
$ARGV Contains the name of the current file when reading from <> or die "cannot bind to port $port! \n";
getsockname Retrieve the sockaddr for a given socket
Assoc Operators Description The array @ARGV contains the command-line arguments getsockopt Get socket options on a given socket
left terms and list operators See below.
@ARGV intended for the script listen(SOCKET, 5) or die "listen: $!";
hex Convert a string to a hexadecimal number
left -> Infix dereference operator %ENV The hash %ENV contains your current environment print "SERVER socket started on port $port\n";
join Join a list into a string using a separator
=++ Auto-increment (magical on strings). Within a subroutine the array @_ contains the parameters
@_ passed to that subroutine # accept a connection kill Send a signal to a process or process group
-- Auto-decrement. my $client_addr;
Contains the list of places that the do EXPR , require, or use length Return the number of bytes in a string
right ** Exponentiation. @INC constructs look for their library files while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
# send message to close connection listen Register your socket as a server
right \ Reference to an object (unary). The name of the current report format for the currently selected
$~ output channel my $name = gethostbyaddr($client_addr, AF_INET ); m Match a string with a regular expression pattern
right ! ~ Unary negation, bitwise complement. print NEW_SOCKET "new socket welcome";
The name of the current top-of-page format for the currently mkdir
$^ print "Connection established $name\n"; Create a directory
right + - Unary plus, minus. selected output channel
close NEW_SOCKET; msgrcv Receive a SysV IPC message from a message queue
Binds a scalar expression to a pattern $^A The current value of the write() accumulator for format() lines
left = ~ }
match. msgsnd Send a SysV IPC message to a message queue
$^L What formats output as a form feed. The default is \f
left ! ~ Same, but negates the result. Client-side Method
The time at which the program began running, in seconds since
my Declare and assign a local variable (lexical scoping)
left * / % x Multiplication, division, modulo, repetition.
$^T the epoch (beginning of 1970)
connect() call -connect( SOCKET, ADDRESS );
package Declare a separate global namespace
The name used to execute the current copy of Perl
Client-side Socket Script Example
left + - . Addition, subtraction, concatenation $^X print Output a list to a filehandle
!/usr/bin/perl -w
left Each element of %! has a true value only if $! is set to that value
>> << Bitwise shift right, bitwise shift left. $! # Filename : clientsocket.pl printf Output redirect to a filehandle
- %ERRNO
named unary The Perl error from the last eval operator, i.e. the last exception push Append one or more elements to an array
E.g. sin, chdir, -f, -M. $@
operators that was caught use strict;
q Singly quote a string
use Socket;
< > <= >= The status returned by the last pipe close, backtick (`` )
Numerical relational operators. qq Doubly quote a string
String relational operators. $? command, successful call to wait() or waitpid(), or from the
lt gt le ge system() operator # start host and port qr Compile pattern
Numerical equal, not equal, compare. my $host = shift || 'localhost';
$. Current line number for the last filehandle accessed. quotemeta
== != <=> Stringwise equal, not equal, compare. my $port = shift || 7999; Quote regular expression magic characters
Compare operators return -1 (less), 0 The current page number of the currently selected output
eq ne cmp (equal) $% my $server = "localhost"; # Host IP address of the server qw Quote a list of words
channel
or 1 (greater). qx
The current page length (printable lines) of the currently Backquote quote a string
$= # create the socket and connect to the port
left & Bitwise AND. selected output channel. The default is 60
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]) rand Retrieve the next pseudorandom number
left | ˆ Bitwise OR, exclusive OR. The number of lines left on the page of the currently selected
$- or die "Cannot create a socket $!\n"; read Fixed-length buffered input from a filehandle
output channel
left && Logical AND. connect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
If set to nonzero, forces a flush right away and after every write readdir Get a directory from a directory handle
$| or die "Cannot connect to port $port! \n";
left || Logical OR. or print on the currently selected output channel
readline Fetch a record from a file
In scalar context, range operator. $0 Contains the name of the program being executed
.. my $line; readpipe
In array context, enumeration. Run a system command and collect standard output
The text matched by the highest used capture group of the last while ($line = <SOCKET>) {
$+ successful search pattern recv Receive a message via a Socket
print "$line\n";
right ? : Conditional (if ? then : else) operator. } rename Change a filename
right = += -= *= etc. Assignment operators.
Run mode options References close SOCKET or die "close: $!";
return Exit function early
Comma operator, also list element -e Single line of script \ reference
rmdir
left , separator. -w Warnings [ ] arrayref
Arrays Remove a directory
Same, enforces the left operand to be a
@arr = (1..3); Array initialization
send Send a message via a socket
left => -c Checks syntax { }
string. hashref
$i = @arr; Number of elements in the array shift Remove the first element of an array
list operators -n Input loop without printing \( ) List of refs
See below. @arr = split(/-/,$text); Split the string into $text shutdown Terminate half of the socket connection
(rightward) -p Printing an input loop
push(@arr, $s); Append $s to @arr socket
-a Automatic split Create a socket
right not Low precedence logical NOT.
$arr = pop(@arr); Removes the last element in the array
-M Load a module sort Sort a list of values
left and Low precedence logical AND. chop(@arr); Removes the last character in the array
-U Unsafe operations mode sqrt Square root function
@ARGV array which stores all the command line arguments
left or xor Low precedence logical OR, exclusive OR. Special variables
-v Version and patch level of script @ENV hash of program’s environment syscall Execute an arbitrary system call

You might also like