{"id":3457,"date":"2014-08-21T00:38:21","date_gmt":"2014-08-20T16:38:21","guid":{"rendered":"http:\/\/rmohan.com\/?p=3457"},"modified":"2014-08-21T00:38:46","modified_gmt":"2014-08-20T16:38:46","slug":"perl-programming-perl-5","status":"publish","type":"post","link":"https:\/\/mohan.sg\/?p=3457","title":{"rendered":"Perl Programming ( perl 5 )"},"content":{"rendered":"<p>Basics<\/p>\n<p>Scripts<\/p>\n<p>Perl is a script language, which is compiled each time before running. That unix knows that it is a perl script there must be the following header at the topline of every perl script: #!\/usr\/bin\/perl where the path to perl has to be correct and the line must not exeed 32 charachters.<br \/>\nComments and Commands<\/p>\n<p>After the header line: #!\/usr\/bin\/perl there are either empty lines with no effect or commandlines or commentary lines. Everything from and behind a &#8220;#&#8221; up to the end of the line is comment and has no effect on the program. Commands start with the first non space charachter on a line and end with a &#8220;;&#8221;. So one can continue a command over several lines and terminates it only with the semicolon.<br \/>\nDirect commands and soubroutines<\/p>\n<p>Normal commands are executed in the order written in the script. But soubroutines can be placed anywhere and will only be evaluated when called from a normal commandline. Perl knows it&#8217;s a soubroutine if it the code is preceeded with a &#8220;sub&#8221; and enclosed in a block like: sub name { command;}<br \/>\nOther special lines<\/p>\n<p>Perl can include other programming code with: require something or with use something.<br \/>\nQuotations<\/p>\n<p>Single quote: &#8221; or: q\/\/<br \/>\nDouble quote: &#8220;&#8221; or: qq\/\/<br \/>\nQuote for execution: &#8220; or: qx\/\/<br \/>\nQuote a list of words: (&#8216;term1&#8242;,&#8217;term2&#8242;,&#8217;term3&#8217;) or: qw\/term1 term2 term3\/<br \/>\nQuote a quoted string: qq\/&#8221;$name&#8221; is $name\/;<br \/>\nQuote something wich contains &#8220;\/&#8221;: qq!\/usr\/bin\/$file is readdy!;<br \/>\nScalar and list context<\/p>\n<p>That perl distinguishes between scalar and list context is the big feature, which makes it uniqe and more usful then most other script languages.<\/p>\n<p>A soubroutine can return lists and not only scalars like in C. Or an array gives the number of elements in a scalar context and the elements itself in a list context.<\/p>\n<p>The enormous value of that feature should be evident.<\/p>\n<p>Variables and Operators<\/p>\n<p>General<\/p>\n<p>There are scalar variables, one and two dimensional arrays and associative arrays. Instead of declaring a variable one preceeds it with a spcial charachter. $variable is a normal scalar variable. @variable is an array and %variable is an associative array. The user of perl does not have to distinguish between a number and a string in a variable. Perl switches the type if neccessary.<br \/>\nScalars<\/p>\n<p>Fill in a scalar with: $price = 300; $name = &#8220;JOHN&#8221;; Calculate with it like: $price *= 2; $price = $oldprice * 4; $count++; $worth&#8211;; Print out the value of a scalar with: print $price,&#8221;\\n&#8221;;<br \/>\nArrays<\/p>\n<p>Fill in a value: $arr[0] = &#8220;Fred&#8221;; $arr[1] = &#8220;John&#8221;; Print out this array: print join(&#8216; &#8216;,@arr),&#8221;\\n&#8221;;<br \/>\nIf two dimensional: $arr[0][0] = 5; $arr[0][1] = 7;<br \/>\nHashes (Associative Arrays)<\/p>\n<p>Fill in a single element with: $hash{&#8216;fred&#8217;} = &#8220;USA&#8221;; $hash{&#8216;john&#8217;} = &#8220;CANADA&#8221;;<\/p>\n<p>Fill in the entire hash:<br \/>\n%a = (<br \/>\n&#8216;r1&#8217;, &#8216;this is val of r1&#8217;,<br \/>\n&#8216;r2&#8217;, &#8216;this is val of r2&#8217;,<br \/>\n&#8216;r3&#8217;, &#8216;this is val of r3&#8217;,<br \/>\n);<br \/>\nor with:<br \/>\n%a = (<br \/>\nr1 =&gt; &#8216;this is val of r1&#8217;,<br \/>\nr2 =&gt; &#8216;this is val of r2&#8217;,<br \/>\nr3 =&gt; &#8216;this is val of r3&#8217;,<br \/>\n);<br \/>\nAssignements<\/p>\n<p>Put something into a variable with a &#8220;=&#8221; or with some combined operator which assignes and and does something at the same time:<\/p>\n<p>$var = &#8220;string&#8221;; Puts the string into $var<br \/>\n$var = 5; Puts a number into $var<\/p>\n<p>$var .= &#8220;string&#8221;; Appends string to $var<br \/>\n$var += 5; Adds number to $var<br \/>\n$var *= 5; Multipliy with 5<br \/>\n$var ||= 5; If $var is 0 make it 5<br \/>\n$var x= 3; Make $var to three times $var as string: from a to aaa<\/p>\n<p>Modify and assigne with:<\/p>\n<p>($new = $old) =~ s\/pattern\/replacement\/;<br \/>\nComparisons<\/p>\n<p>Compare strings with: eq ne like in: $name eq &#8220;mary&#8221;.<br \/>\nCompare numbers with: == != &gt;= &lt;= &lt;=&gt; like in: $price == 400.<\/p>\n<p>And\/Or\/Not<\/p>\n<p>Acct on success or failure of an expression: $yes or die; means exit if $yes is not set.<br \/>\nFor AND we have: &amp;&amp; and &#8220;and&#8221; and for OR we have: || or &#8220;or&#8221;. Not is &#8220;!&#8221; or &#8220;not&#8221;.<\/p>\n<p>AND,OR and NOT are regularly used in if() statements:<br \/>\nif($first &amp;&amp; $second){&#8230;.;}<br \/>\nif($first || $second){&#8230;.;}<br \/>\nif($first &amp;&amp; ! $second{&#8230;.;} means that $first must be non zero but $second must not be so.<br \/>\nBut many NOT&#8217;s can be handled more reasonable with the unless() statement. Instead:<br \/>\nprint if ! $noway; one uses: print unless $noway;<\/p>\n<p>.<\/p>\n<p>Branching<\/p>\n<p>if<\/p>\n<p>if(condition){<br \/>\ncommand;<br \/>\n}elsif(condition){<br \/>\ncommand;<br \/>\n}else{<br \/>\ncommand;<br \/>\n}<\/p>\n<p>command if condition;<br \/>\nunless (just the opposite of if)<\/p>\n<p>unless(condition){<br \/>\ncommand;<br \/>\n}else{<br \/>\ncommand;<br \/>\n}<\/p>\n<p>command unless condition;<br \/>\nLooping<\/p>\n<p>while<\/p>\n<p>while(condition){<br \/>\ncommand;<br \/>\n}<\/p>\n<p># Go prematurely to the next iteration<br \/>\nwhile(condition){<br \/>\ncommand;<br \/>\nnext if condition;<br \/>\ncommand;<br \/>\n}<\/p>\n<p># Prematureley abort the loop with last<br \/>\nwhile(condition){<br \/>\ncommand;<br \/>\nlast if condition;<br \/>\n}<\/p>\n<p># Prematureley continue the loop but do continue{} in any case<br \/>\nwhile(condition){<br \/>\ncommand;<br \/>\ncontinue if condition;<br \/>\ncommand;<br \/>\n}continue{<br \/>\ncommand;<br \/>\n}<\/p>\n<p># Redo the loop without evaluating while(condtion)<br \/>\nwhile(condtion){<br \/>\ncommand;<br \/>\nredo if condition;<br \/>\n}<\/p>\n<p>command while condition;<br \/>\nuntil (just the opposite of while)<\/p>\n<p>until(condition){<br \/>\ncommand;<br \/>\n}<\/p>\n<p>until(condition){<br \/>\ncommand;<br \/>\nnext if condition;<br \/>\ncommand;<br \/>\n}<\/p>\n<p>until(condition){<br \/>\ncommand;<br \/>\nlast if condition;<br \/>\n}<\/p>\n<p>until(condition){<br \/>\ncommand;<br \/>\ncontinue if condition;<br \/>\ncommand;<br \/>\n}continue{<br \/>\ncommand;<br \/>\n}<\/p>\n<p>command until condtion;<br \/>\nfor (=foreach)<\/p>\n<p># Iterate over @data and have each value in $_<br \/>\nfor(@data){<br \/>\nprint $_,&#8221;\\n&#8221;;<br \/>\n}<\/p>\n<p># Get each value into $info iteratively<br \/>\nfor $info (@data){<br \/>\nprint $info,&#8221;\\n&#8221;;<br \/>\n}<\/p>\n<p># Iterate over a range of numbers<br \/>\nfor $num (1..100){<br \/>\nnext if $num % 2;<br \/>\nprint $num,&#8221;\\n&#8221;;<br \/>\n}<\/p>\n<p># Eternal loop with (;;)<br \/>\nfor (;;){<br \/>\n$num++;<br \/>\nlast if $num &gt; 100;<br \/>\n}<br \/>\nmap<\/p>\n<p># syntax<br \/>\nmap (command,list);<br \/>\nmap {comm1;comm2;comm3;} list;<br \/>\n# example<br \/>\nmap (rename($_,lc($_),&lt;*&gt;);<br \/>\n.<br \/>\nFile Test Operators<\/p>\n<p>File test operators check for the status of a file: Some examples:<br \/>\n-f $file It&#8217;s a plain file<br \/>\n-d $file It&#8217;s a directory<br \/>\n-r $file Readable file<br \/>\n-x $file Executable file<br \/>\n-w $file Writable file<br \/>\n-o $file We are owner<br \/>\n-l $file File is a link<br \/>\n-e $file File exists<br \/>\n-z $file File has zero size, but exists<br \/>\n-s $file File is greater than zero<br \/>\n-t FILEHANDLE This filehandle is connetcted to a tty<br \/>\n-T $file Textfile<br \/>\n-B $file Binary file<br \/>\n-M $file Returns the day number of last modification time<\/p>\n<p>Regular Expressions<\/p>\n<p>What it is<\/p>\n<p>A regular expression is an abstract formulation of a string. Usually one has a search pattern and a match which is the found string. There is also a replacement for the match, if a substitution is made.<br \/>\nPatterns<\/p>\n<p>A pattern stands for either one, any number, several, a particular number or none cases of a character or a charachter-set given literaly, abstractly or octaly.<br \/>\nPATTERN MATCH<br \/>\n. any character (dot)<br \/>\n.* any number on any character (dot asterix)<br \/>\na* the maximum of consecutive a&#8217;s<br \/>\na*? the minimum of consecutive a&#8217;s<br \/>\n.? one or none of any characters<br \/>\n.+ one or more of any character<br \/>\n.{3,7} three up to seven of any characters, but as many as possible<br \/>\n.{3,7}? three up to seven, but the fewest number possible<br \/>\n.{3,} at least 3 of any charachter<br \/>\n.{3} exactly 3 times any character<br \/>\n[ab] a or b<br \/>\n[^ab] not a and also not b<br \/>\n[a-z] any of a through z<br \/>\n^a<br \/>\n\\Aa a at begining of string<br \/>\na$<br \/>\na\\Z a at end of string<br \/>\nA|bb|CCC A or bb or CCC<br \/>\ntele(f|ph)one telefone or telephone<br \/>\n\\w A-Z or a-z or _<br \/>\n\\W none of the above<br \/>\n\\d 0-9<br \/>\n\\D none of 0-9<br \/>\n\\s space or \\t or \\n (white space)<br \/>\n\\S non space<br \/>\n\\t tabulator<br \/>\n\\n newline<br \/>\n\\r carridge return<br \/>\n\\b word boundary<br \/>\n\\bkey matches key but not housekey<br \/>\n(?#&#8230;&#8230;.) Comment<br \/>\n(?i) Case insensitive match. This can be inside a pattern variable.<br \/>\n(?:a|b|c) a or b or c, but without string in $n<br \/>\n(?=&#8230;..) Match &#8230;.. but do not store in $&amp;<br \/>\n(?!&#8230;..) Anything but &#8230;.. and do not store in $&amp;<br \/>\nSubstitututions<\/p>\n<p>One can replace found matches with a replacement with the s\/pattern\/replacement\/; statement.<br \/>\nThe &#8220;s&#8221; is the command. Then there follow three delimiters with first a search pattern and second a replacement between them. If there are &#8220;\/&#8221; withing the pattern or the replacement then one chooses another delimiter than &#8220;\/&#8221; for instance a &#8220;!&#8221;.<\/p>\n<p>To change the content of a variable do: $var =~ s\/pattern\/replacement\/;<br \/>\nTo put the changed value into another variable, without distorting the original variable do:<br \/>\n($name = $line) =~ s\/^(\\w+).*$\/$1\/;<br \/>\nCOMMAND WHAT it DOES<br \/>\ns\/A\/B\/; substitute the first a in a string with B<br \/>\ns\/A\/B\/g; substitute every a with a B<br \/>\ns\/A+\/A\/g; substitute any number of a with one A<br \/>\ns\/^#\/\/; substitute a leading # with nothing. i.e remove it<br \/>\ns\/^\/#\/; prepend a # to the string<br \/>\ns\/A(\\d+)\/B$1\/g; substitute a followed by a number with b followed by the same number<br \/>\ns\/(\\d+)\/$1*3\/e; substitute the found number with 3 times it&#8217;s value<br \/>\nUse two &#8220;e&#8221; for to get an eval effect:<br \/>\nperl -e &#8216;$aa = 4; $bb = &#8216;$aa&#8217;; $bb =~ s\/(\\$\\w+)\/$1\/ee; print $bb,&#8221;\\n&#8221;;&#8217;<br \/>\ns\/here goes date\/$date\/g; substitute &#8220;here goes date&#8221; with the value of $date<br \/>\ns\/(Masumi) (Nakatomi)\/$2 $1\/g; switch the two terms<br \/>\ns\/\\000\/\/g; remove null charachters<br \/>\ns\/$\/\\033\/; append a ^M to make it readable for dos<br \/>\nInput and Output<\/p>\n<p>Output a value from a variable<\/p>\n<p>print $var,&#8221;\\n&#8221;;<br \/>\nOutput a formated string<\/p>\n<p>printf(&#8220;%-20s%10d&#8221;,$user,$wage);<br \/>\nRead in a value into a variable and remove the newline<\/p>\n<p>chomp() (perl5) removes a newline if one is there. The chop() (perl4) removes any last character.<\/p>\n<p>chomp($var = );<br \/>\nRead in a file an process it linewise<\/p>\n<p>open(IN,&#8221;&lt;filename&#8221;) || die &#8220;Cannot open filename for input\\n&#8221;;<br \/>\nwhile(){<br \/>\ncommand;<br \/>\n}<br \/>\nclose IN;<br \/>\nRead a file into an array<\/p>\n<p>open(AAA,&#8221;&lt;infile&#8221;) || die &#8220;Cannot open infile\\n&#8221;;<br \/>\n@bigarray = ;<br \/>\nclose AAA;<br \/>\nOutput into a file<\/p>\n<p>open(OUT,&#8221;&gt;file&#8221;) || die &#8220;Cannot oben file for output\\n&#8221;;<br \/>\nwhile(condition){<br \/>\nprint OUT $mystuff;<br \/>\n}<br \/>\nclose OUT;<br \/>\nCheck, whether open file would yield something (eof)<\/p>\n<p>open(IN,&#8221;&lt;file&#8221;) || die &#8220;Cannot open file\\n&#8221;;<br \/>\nif(eof(IN)){<br \/>\nprint &#8220;File is empty\\n&#8221;;<br \/>\n}else{<br \/>\nwhile(){<br \/>\nprint;<br \/>\n}<br \/>\n}<br \/>\nclose IN;<br \/>\nProcess Files mentioned on the Commandline<\/p>\n<p>The empty filehandle &#8220;&lt;&gt;&#8221; reads in each file iteratively. The name of the current processed file is in $ARGV. For example print each line of several files prepended with it&#8217;s filename:<br \/>\nwhile(&lt;&gt;){<br \/>\n$file = $ARGV;<br \/>\nprint $file,&#8221;\\t&#8221;,$_;<br \/>\nopen(IN,&#8221;&lt;$file&#8221;) or warn &#8220;Cannot open $file\\n&#8221;;<br \/>\n&#8230;.commands for this file&#8230;.<br \/>\nclose(IN);<br \/>\n}<br \/>\nGet Filenames<\/p>\n<p>Get current directory at once<\/p>\n<p>@dir = &lt;*&gt;;<br \/>\nUse current directory iteratively<\/p>\n<p>while(&lt;*&gt;){<br \/>\n&#8230;commands&#8230;<br \/>\n}<br \/>\nSelect files with &lt;&gt;<\/p>\n<p>@files = ;<br \/>\nSelect files with glob()<\/p>\n<p>This is the official way of globbing:<br \/>\n@files = glob(&#8220;$mypatch\/*$suffix&#8221;);<\/p>\n<p>Readdir()<\/p>\n<p>Perl can also read a directory itself, without a globbing shell. This is faster and more controllable, but one has to use opendir() and closedir().<br \/>\nopendir(DIR,&#8221;.&#8221;) or die &#8220;Cannot open dir.\\n&#8221;;<br \/>\nwhile(readdir DIR){<br \/>\nrename $_,lc($_);<br \/>\n}<br \/>\nclosedir(DIR);<br \/>\nPipe Input and Output from\/to Unix Commands<\/p>\n<p>Process Data from a Unix Pipe<\/p>\n<p>open(IN,&#8221;unixcommand|&#8221;) || die &#8220;Could not execute unixcommand\\n&#8221;;<br \/>\nwhile(){<br \/>\ncommand;<br \/>\n}<br \/>\nclose IN;<br \/>\nOutput Data into a Unix Pipe<\/p>\n<p>open(OUT,&#8221;|more&#8221;) || die &#8220;Could not open the pipe to more\\n&#8221;;<br \/>\nfor $name (@names){<br \/>\n$length = length($name);<br \/>\nprint OUT &#8220;The name $name consists of $lenght characters\\n&#8221;;<br \/>\n}<br \/>\nclose OUT;<br \/>\nExecute Unix Commands<\/p>\n<p>Execute a Unix Command and forget about the Output<\/p>\n<p>system(&#8220;someprog -auexe -fv $filename&#8221;);<br \/>\nExecute a Unix Command an store the Output into a Variable<\/p>\n<p>If it&#8217;s just one line or a string:<\/p>\n<p>chomp($date = qx!\/usr\/bin\/date!); The chomp() (perl5) removes the trailing &#8220;\\n&#8221;. $date gets the date.<\/p>\n<p>If it gives a series of lines one put&#8217;s the output into an array:<\/p>\n<p>chomp(@alllines = qx!\/usr\/bin\/who!);<br \/>\nReplace the whole perl program by a unix program<\/p>\n<p>exec anotherprog; But then the perl program is gone.<\/p>\n<p>The Perl builtin Functions<\/p>\n<p>String Functions<\/p>\n<p>Get all upper case with: $name = uc($name);<br \/>\nGet only first letter uppercase: $name = ucfirst($name);<br \/>\nGet all lowercase: $name = lc($name);<br \/>\nGet only first letter lowercase: $name = lcfirst($name);<br \/>\nGet the length of a string: $size = length($string);<br \/>\nExtract 5-th to 10-th characters from a string: $part = substr($whole,4,5);<br \/>\nRemove line ending: chomp($var);<br \/>\nRemove last character: chop($var);<br \/>\nCrypt a string: $code = crypt($word,$salt);<br \/>\nExecute a string as perl code: eval $var;<br \/>\nShow position of substring in string: $pos = index($string,$substring);<br \/>\nShow position of last substring in string: $pos = rindex($string,$substring);<br \/>\nQuote all metacharachters: $quote = quotemeta($string);<br \/>\nArray Functions<\/p>\n<p>Get expressions for which a command returned true: @found = grep(\/[Jj]ohn\/,@users);<br \/>\nApplay a command to each element of an array: @new = map(lc($_),@start);<br \/>\nPut all array elements into a single string: $string = join(&#8216; &#8216;,@arr);<br \/>\nSplit a string and make an array out of it: @data = split(\/&amp;\/,$ENV{&#8216;QUERY_STRING&#8217;};<br \/>\nSort an array: sort(@salery);<br \/>\nReverse an array: reverse(@salery);<br \/>\nGet the keys of a hash(associative array): keys(%hash);<br \/>\nGet the values of a hash: values(%hash);<br \/>\nGet key and value of a hash iteratively: each(%hash);<br \/>\nDelete an array: @arr = ();<br \/>\nDelete an element of a hash: delete $hash{$key};<br \/>\nCheck for a hash key: if(exists $hash{$key}){;}<br \/>\nCheck wether a hash has elements: scalar %hash;<br \/>\nCut of last element of an array and return it: $last = pop(@IQ_list);<br \/>\nCut of first element of an array and return it: $first = shift(@topguy);<br \/>\nAppend an array element at the end: push(@waiting,$name);<br \/>\nPrepend an array element to the front: unshift(@nowait,$name);<br \/>\nRemove first 2 chars an replace them with $var: splice(@arr,0,2,$var);<br \/>\nGet the number of elements of an array: scalar @arr;<br \/>\nGet the last index of an array: $lastindex = $#arr;<br \/>\nFile Functions<\/p>\n<p>Open a file for input: open(IN,&#8221;\/path\/file&#8221;) || die &#8220;Cannot open file\\n&#8221;;<br \/>\nOpen for appending: open(OUT,&#8221;&gt;&gt;$file&#8221;) || &amp;myerr(&#8220;Couldn&#8217;t open $file&#8221;);<br \/>\nClose a file: close OUT;<br \/>\nSet permissions: chmod 0755, $file;<br \/>\nDelete a file: unlink $file;<br \/>\nRename a file: rename $file, $newname;<br \/>\nMake a hard link: link $existing_file, $link_name;<br \/>\nMake a symbolic link: symlink $existing_file, $link_name;<br \/>\nMake a directory: mkdir $dirname, 0755;<br \/>\nDelete a directory: rmdir $dirname;<br \/>\nReduce a file&#8217;s size: truncate $file, $size;<br \/>\nChange owner- and group-ID: chown $uid, $gid;<br \/>\nFind the real file of a symlink: $file = readlink $linkfile;<br \/>\nGet all the file infos: @stat = stat $file;<br \/>\nConversions Functions<\/p>\n<p>Number to character: chr $num;<br \/>\nCharachter to number: ord($char);<br \/>\nHex to decimal: hex(0x4F);<br \/>\nOctal to decimal: oct(0700);<br \/>\nGet localtime from time: localtime(time);<br \/>\nGet greenwich meantime: gmtime(time);<br \/>\nPack variables into string: $string = pack(&#8220;C4&#8221;,split(\/\\.\/,$IP));<br \/>\nUnpack the above string: @arr = unpack(&#8220;C4&#8221;,$string);<br \/>\nSubroutines (=functions in C++)<\/p>\n<p>Define a Subroutine<\/p>\n<p>sub mysub {<br \/>\ncommand;<br \/>\n}<br \/>\nExample:<br \/>\nsub myerr {<br \/>\nprint &#8220;The following error occured:\\n&#8221;;<br \/>\nprint $_[0],&#8221;\\n&#8221;;<br \/>\n&amp;cleanup;<br \/>\nexit(1);<br \/>\n}<br \/>\nCall a Subroutine<\/p>\n<p>&amp;mysub;<br \/>\nGive Arguments to a Subroutine<\/p>\n<p>&amp;mysub(@data);<br \/>\nReceive Arguments in the Subroutine<\/p>\n<p>As global variables:<br \/>\nsub mysub {<br \/>\n@myarr = @_;<br \/>\n}<br \/>\nsub mysub {<br \/>\n($dat1,$dat2,$dat3) = @_;<br \/>\n}<br \/>\nAs local variables:<br \/>\nsub mysub {<br \/>\nlocal($dat1,$dat2,$dat3) = @_;<br \/>\n}<\/p>\n<p>Some of the Special Variables<\/p>\n<p>SYNTAX<\/p>\n<p>MEANING<\/p>\n<p>$_ String from current loop. e.g. for(@arr){ $field = $_ . &#8221; ok&#8221;; }<br \/>\n$. Line number from current file processed with: while(){<br \/>\n$0 Programname<br \/>\n$$ Process id of current program<br \/>\n$&lt; The real uid of current program $&gt; Effektive uid of current program<br \/>\n$| For flushing output: select XXX; $| = 1;<br \/>\n$&amp; The match of the last patternsearch<br \/>\n$1&#8230;. The ()-embraced matches of the last patternsearch<br \/>\n$` The string to the left of the last match<br \/>\n$&#8217; The string to the right of the last match<\/p>\n<p>Forking<\/p>\n<p>Forking is very easy! Just fork. One puts the fork in a three way if(){} to separately the parent, the child and the error.<br \/>\nif($pid = fork){<br \/>\n# Parent<br \/>\ncommand;<br \/>\n}elsif($pid == 0){<br \/>\n# Child<br \/>\ncommand;<br \/>\n# The child must end with an exit!!<br \/>\nexit;<br \/>\n}else{<br \/>\n# Error<br \/>\ndie &#8220;Fork did not work\\n&#8221;;<br \/>\n}<\/p>\n<p>Building Pipes for forked Children<\/p>\n<p>Building a Pipe<\/p>\n<p>pipe(READHANDLE,WRITEHANDLE);<br \/>\nFlushing the Pipe<\/p>\n<p>select(WRITEHANDLE); $| = 1; select(STDOUT);<br \/>\nSetting up two Pipes between the Parent and a Child<\/p>\n<p>pipe(FROMCHILD,TOCHILD); select(TOCHILD); $| = 1; select(STDOUT);<br \/>\npipe(FROMPARENT,TOPARENT);select(TOPARENT);$| = 1; select(STDOUT);<\/p>\n<p>if($pid = fork){<br \/>\n# Parent<br \/>\nclose FROMPARENT;<br \/>\nclose TOPARENT;<br \/>\ncommand;<br \/>\n}elsif($pid == 0){<br \/>\n# Child<br \/>\nclose FROMCHILD;<br \/>\nclose TOCHILD;<br \/>\ncommand;<br \/>\nexit;<br \/>\n}else{<br \/>\n# Error<br \/>\ncommand;<br \/>\nexit;<br \/>\n}<br \/>\nBuilding a Socket Connection to another Computer<\/p>\n<p># Somwhere at the beginning of the script<br \/>\nrequire 5.002;<br \/>\nuse Socket;<br \/>\nuse sigtrap;<\/p>\n<p># Prepare infos<br \/>\n$port = 80;<br \/>\n$remote = &#8216;remotehost.domain&#8217;;<br \/>\n$iaddr = inet_aton($remote);<br \/>\n$paddr = sockaddr_in($port,$iaddr);<\/p>\n<p># Socket<br \/>\nsocket(S,AF_INET,SOCK_STREAM,$proto) or die $!;<\/p>\n<p># Flush socket<br \/>\nselect(S); $| = 1; select(STDOUT);<\/p>\n<p># Connect<br \/>\nconnect(S,$paddr) or die $!;<\/p>\n<p># Print to socket<br \/>\nprint S &#8220;something\\n&#8221;;<\/p>\n<p># Read from socket<br \/>\n$gotit = <s>;<\/s><\/p>\n<p># Or read a single character only<br \/>\nread(S,$char,1);<\/p>\n<p># Close the socket<br \/>\nclose(S);<br \/>\nGet Unix User and Network Informations<\/p>\n<p>Get the password entry for a particular user with: @entry = getpwnam(&#8220;$user&#8221;);<br \/>\nOr with bye user ID: @entry = getpwuid(&#8220;$UID&#8221;);<\/p>\n<p>One can informations for group, host, network, services, protocols in the above way with the commands: getgrnam, getgrid, gethostbyname, gethostbyaddr, getnetbyname, getnetbyaddr, getservbyname, getservbyport, getprotobyname, getprotobynumber.<\/p>\n<p>If one wants to get all the entries of a particular categorie one can loop through them by:<\/p>\n<p>setpwent;<br \/>\nwhile(@he = getpwent){<br \/>\ncommands&#8230;<br \/>\n}<br \/>\nentpwent;<\/p>\n<p>For example: Get a list of all users with their homedirectories:<br \/>\nsetpwent;<br \/>\nwhile(@he = getpwent){<br \/>\nprintf(&#8220;%-20s%-30s\\n&#8221;,$he[0],$he[7]);<br \/>\n}<br \/>\nendpwent;<br \/>\nThe same principle works for all the above data categories. But most of them need a &#8220;stayopen&#8221; behind the set command.<\/p>\n<p>Arithmetics<\/p>\n<p>Addition: +<br \/>\nSubtraction: &#8211;<br \/>\nMultiplication: *<br \/>\nDivision: \/<br \/>\nRise to the power of: **<br \/>\nRise e to the pwoer of: exp()<br \/>\nModulus: %<br \/>\nSquare root: sqrt()<br \/>\nAbsolut value: abs()<br \/>\nTangens: atan2()<br \/>\nSinus: sin()<br \/>\nCosine: cos()<br \/>\nRandom number: rand()<\/p>\n<p>Formatting Output with &#8220;format&#8221;<\/p>\n<p>This should be simplification of the printf formatting. One formats once only and then it will be used for every write to a specified filehandle. Prepare a format somwhere in the program:<\/p>\n<p>format filehandle =<br \/>\n@&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;@###.#####@&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;@||||||||||<br \/>\n$var1, $var3, $var4<br \/>\n.<\/p>\n<p>Now use write to print into that filhandle according to the format:<\/p>\n<p>write FILEHANDLE;<\/p>\n<p>The @&lt;&lt;&lt; does left adjustment, the @&gt;&gt;&gt; right adjustment, @##.## is for numericals and @||| centers.<\/p>\n<p>Command line Switches<\/p>\n<p>Show the version number of perl: perl -v;<br \/>\nCheck a new program without runing it: perl -wc ;<br \/>\nHave an editing command on the command line: perl -e &#8216;command&#8217;;<br \/>\nAutomatically print while precessing lines: perl -pe &#8216;command&#8217; ;<br \/>\nRemove line endings and add them again: perl -lpe &#8216;command&#8217; ;<br \/>\nEdit a file in place: perl -i -pe &#8216;command&#8217; ;<br \/>\nAutosplit the lines while editing: perl -a -e &#8216;print if $F[3] =~ \/ETH\/;&#8217; ;<br \/>\nHave an input loop without printing: perl -ne &#8216;command&#8217; ;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Basics<\/p>\n<p>Scripts<\/p>\n<p>Perl is a script language, which is compiled each time before running. That unix knows that it is a perl script there must be the following header at the topline of every perl script: #!\/usr\/bin\/perl where the path to perl has to be correct and the line must not exeed 32 charachters. Comments [&#8230;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[64],"tags":[],"_links":{"self":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/3457"}],"collection":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3457"}],"version-history":[{"count":1,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/3457\/revisions"}],"predecessor-version":[{"id":3458,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/3457\/revisions\/3458"}],"wp:attachment":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3457"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3457"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3457"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}