Network Programming with Perl Cheat Sheet Series
Total Page:16
File Type:pdf, Size:1020Kb
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 number perldoc perldoc Look up Perl documentation in Pod format mal] $var[20] 21st element of array @var accept Accept an incoming socket connection perldoc perltoc Perl documentation Table of Contents (ToC) Turns on autosplit mode when used with a -n or -p -a $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 -c $$p[20] 21st element of array referenced by $p binmode Prepare binary files for input/output perldoc perlfunc List of built-in Perl functions without executing it $var[-1] Last element of array @var perldoc -f <function_name> Help with a specific function -C [number/list] The -C flag controls some of the Perl Unicode features. chdir Change current working directory perldoc perlop List of Perl operators and precedence $var[$x][$y] $y-th element of $x-th element of array @var -d, -dt Runs the program under the Perl debugger chmod Changes the permissions on a file/list of files perldoc perlmodlib For constructing perl modules and finding existing ones $var{’JAN’} A value from ‘hash’ %var chop Remove the last character from a string perldoc perllocal Locally installed modules list (if any) -Dletters, Sets debugging flags (only if your perl binary has been built with debugging enabled) $p = \%var Now $p is a reference to hash %var chown perldoc <module_name> Documentation for specific module -Dnumber Change the ownership of the file -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 -E commandline Close directory 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 -h Prints summary if the options Less than or equal <= le The entire hash; %var die Raise an exception -m -mmodule executes use module (); before executing your program Greater than or equal >= ge Emulates a multidimensional array; $var{’a’,1,...} 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 -p Input loop in the script with line printing Server-side Method Boolean operators 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 bind() call -bind( SOCKET, ADDRESS ); exp Exponential C-style Logical AND && ($a && $b) is false -T Turns on taint so you can test listen() call- listen( SOCKET, QUEUESIZE ); fork operator Create a new process just like the existing one accept() call - accept( NEW_SOCKET, SOCKET ); -v Prints the version and patchlevel of your perl executable Logical AND operator and ($a and $b) is false 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 operator #!/usr/bin/perl -w getlogin Return who is logged in at this TTY -w Prints warnings about dubious constructs # Filename : serversocket.pl 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 Default variable Get protocol record given name $ my $port = shift || 7999; getprotobynumber Quotes ($foo = 5;) $/ The input record separator, newline by default my $proto = getprotobyname('tcp'); Get protocol record numeric protocol Single-quotes - Literal my $server = "localhost"; # Host IP running the server getprotoent Get next protocols record $bar = 'it is worth $foo'; it is worth $foo $\ The output record separator for the print operator 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"; $& The string matched by the last successful pattern match getpwuid 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 $bar = q(it is 'worth' $foo); it is 'worth' $foo getservbyport 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 successful pattern match getservent Get next services record 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 @ARGV Get socket options on a given socket left terms and list operators See below. 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 Within a subroutine the array @_ contains the parameters =++ Auto-increment (magical on strings). @_ 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 @INC length Return the number of bytes in a string right ** Exponentiation. 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 The name of the current report format for the currently selected right \ Reference to an object (unary). $~ 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 Create a directory right + - Unary plus, minus. selected output channel print "Connection established $name\n"; 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) $^T connect() call -connect( SOCKET, ADDRESS ); left * / % x Multiplication, division, modulo, repetition. the epoch (beginning of 1970) package Declare a separate global namespace Client-side Socket Script Example The name used to execute the current copy of Perl left + - . Addition, subtraction, concatenation $^X print Output a list to a filehandle !/usr/bin/perl -w Each element of %! has a true value only if $! is set to that value left >> << Bitwise shift right, bitwise shift left. $! printf Output redirect to a filehandle - %ERRNO # Filename : clientsocket.pl named unary push Append one or more elements to an array E.g. sin, chdir, -f, -M. The Perl error from the last eval operator, i.e. the last exception $@ use strict; operators that was caught q use Socket; Singly quote a string < > <= >= 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 # start host and port system() operator qr Compile pattern Numerical equal, not equal, compare. my $host = shift || 'localhost'; $. Current line number for the last filehandle accessed. == != <=> Stringwise equal, not equal, compare. my $port = shift || 7999; quotemeta Quote regular expression magic characters Compare operators return -1 (less), 0 The current page number of the currently selected output $% my $server = "localhost"; # Host IP address of the server qw Quote a list of words eq ne cmp (equal) channel or 1 (greater). The current page length (printable lines) of the currently qx 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 The number of lines left on the page of the currently selected left | ˆ Bitwise OR, exclusive OR.