Network Programming With Perl Cheat Sheet
Network Programming With Perl Cheat Sheet
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