Perl: Difference between revisions

From wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(20 intermediate revisions by the same user not shown)
Line 1: Line 1:
I'm leaving Perl, traded it for Python.
[[Category:Programming]]
Some shortcuts I'd like to remember
=Warnings=
===Put a ; at the end of each line===
This is still what I forget most.


Print out the contents of $variable in a structured format.
===autovivification===
:If testing for existence of a hash key beware that all intermediate keys will be created by the test. In below example <code>$hash1($key1}</code> will be created if it does not exist yet.
<syntaxhighlight lang=Perl>
if (exists $hash1{$key1}{$key2) {
    ...
} else {
    ...
}
)
</syntaxhighlight>
=Things that do work=
 
Searching and matching is explained in [[Regular Expressions]].
 
;perl -e '<commands>'
:Execute <commnands>
 
;Print out the contents of $variable in a structured format:
<syntaxhighlight lang=Perl>
<syntaxhighlight lang=Perl>
use Data::Dumper;
use Data::Dumper;
print Dumper($variable);
print Dumper($variable);
</syntaxhighlight>
if-then-else:
<syntaxhighlight lang=Perl>
if < expr > {
<codeblock>
} elsif < expr ) {
<codeblock>
} else {
<codeblock>
}
</syntaxhighlight>
</syntaxhighlight>


Line 14: Line 44:
:Concatenate $string and $addstring
:Concatenate $string and $addstring


;$string = s/<regexp>/<newvalue>/[g]
;$string =~ s/<regexp>/<newvalue>/[g]
:Substitute <regexp> with <newvalue> in $string. The g modifier makes the all occurrences of <regexp> are substituted.
:Substitute <regexp> with <newvalue> in $string. The g modifier makes the all occurrences of <regexp> are substituted.


Line 22: Line 52:
;sprintf(format,$string)
;sprintf(format,$string)
:Return formatted string. format is e.g. "%.3f". Check [[Python:Strings#Advanced]] for all formats.
:Return formatted string. format is e.g. "%.3f". Check [[Python:Strings#Advanced]] for all formats.
;$exitcode = system("a command")
:Executed the command in a subprocess and return the exitcode
;$output = `a command`
:Execute the command and return all command output
;sleep(x)
:Sleep for x seconds
;$|++
:Set standard output to unbuffered, every is put on screen immediately.
;$username = getpwuid($<)
:Get the username of the one executing the script. $< is the uid of the current user.
==Hashes==
;%newhash = (%oldhas1,%oldhash3)
;$newhashref = {$oldhasref1,$oldhashref3}
:Merge 2 hashes, works if all keys are unique
==Arrays==
;arr1 = split(<sep>,$string)
:Split a string in to an array on <sep>
;a = arr1[0]
:First element in arr1
;a = arr1[-1]
:Last element in arr1
;if ( grep(/^<value>$/,@arr1) )
:Check if <value> exist in arr1 (Note the ^ and $  for an exact match
==Files==
;open (FH, "< filename") || die("Open failed for filename")
:Open filename for reading on filehandle FH. Exit the program when the open failed
;@array = <FH>
:Read the file opened on FH into @array (1 element per line
;while ( line = (<FH>) )
:Read the file opened on FH line by line
==Flow control==
The usual works (if-then-else, for , foreach)
;||die("message")
:|| causes the statement only to be executed if the previous failed. Stop the program and write messaged to standard error.
;|| do {codeblock};
:Like die but not exiting the program, use to do additional actions on the failure of the previous command
==Compare==
;==, !=, >=, >, <, etc
:Compare numeric data
;eq, ne, ge, gt, lt, etc
:Compare strings

Latest revision as of 13:18, 15 January 2026

Warnings

Put a ; at the end of each line

This is still what I forget most.

autovivification

If testing for existence of a hash key beware that all intermediate keys will be created by the test. In below example $hash1($key1} will be created if it does not exist yet.
if (exists $hash1{$key1}{$key2) {
    ...
} else {
    ...
}
)

Things that do work

Searching and matching is explained in Regular Expressions.

perl -e '<commands>'
Execute <commnands>
Print out the contents of $variable in a structured format
use Data::Dumper;
print Dumper($variable);

if-then-else:

if < expr > {
 <codeblock>
} elsif < expr ) {
 <codeblock>
} else {
 <codeblock>
}
$var += <value>
Add <value> to $var (works for -, *, / too)
$string .= $addstring
Concatenate $string and $addstring
$string =~ s/<regexp>/<newvalue>/[g]
Substitute <regexp> with <newvalue> in $string. The g modifier makes the all occurrences of <regexp> are substituted.
$newstring = substr($string,start,length)
Return substring of $string
sprintf(format,$string)
Return formatted string. format is e.g. "%.3f". Check Python:Strings#Advanced for all formats.
$exitcode = system("a command")
Executed the command in a subprocess and return the exitcode
$output = `a command`
Execute the command and return all command output
sleep(x)
Sleep for x seconds
$|++
Set standard output to unbuffered, every is put on screen immediately.
$username = getpwuid($<)
Get the username of the one executing the script. $< is the uid of the current user.

Hashes

%newhash = (%oldhas1,%oldhash3)
$newhashref = {$oldhasref1,$oldhashref3}
Merge 2 hashes, works if all keys are unique

Arrays

arr1 = split(<sep>,$string)
Split a string in to an array on <sep>
a = arr1[0]
First element in arr1
a = arr1[-1]
Last element in arr1
if ( grep(/^<value>$/,@arr1) )
Check if <value> exist in arr1 (Note the ^ and $ for an exact match

Files

open (FH, "< filename") || die("Open failed for filename")
Open filename for reading on filehandle FH. Exit the program when the open failed
@array = <FH>
Read the file opened on FH into @array (1 element per line
while ( line = (<FH>) )
Read the file opened on FH line by line

Flow control

The usual works (if-then-else, for , foreach)

||die("message")
|| causes the statement only to be executed if the previous failed. Stop the program and write messaged to standard error.
|| do {codeblock};
Like die but not exiting the program, use to do additional actions on the failure of the previous command

Compare

==, !=, >=, >, <, etc
Compare numeric data
eq, ne, ge, gt, lt, etc
Compare strings