Perl is a dynamic, dynamically-typed, high-level, scripting (interpreted) language most comparable with PHP and Python. Perl's syntax owes a lot to ancient shell scripting tools, and it is famed for its overuse of confusing symbols, the majority of which are impossible to Google for. Perl's shell scripting heritage makes it great for writing glue code: scripts which link together other scripts and programs. Perl is ideally suited for processing text data and producing more text data. Perl is widespread, popular, highly portable and well-supported. Perl was designed with the philosophy "There's More Than One Way To Do It" (TMTOWTDI) (contrast with Python, where "there should be one - and preferably only one - obvious way to do it").
Perl has horrors, but it also has some great redeeming features. In this respect it is like every other programming language ever created.
This document is intended to be informative, not evangelical. It is aimed at people who, like me:
This document is intended to be as short as possible, but no shorter.
The following can be said of almost every declarative statement in this document: "that's not, strictly speaking, true; the situation is actually a lot more complicated". If you see a serious lie, point it out, but I reserve the right to preserve certain critical lies-to-children.
Throughout this document I'm using example print
statements to output data but not explicitly appending line breaks. This is done to prevent me from going crazy and to give greater attention to the actual string being printed in each case, which is invariably more important. In many examples, this results in alotofwordsallsmusheduptogetherononeline if the code is run in reality. Try to ignore this.
A Perl script is a text file with the extension .pl
.
Here's the full text of helloworld.pl
:
use strict; use warnings; print "Hello world";
Perl scripts are interpreted by the Perl interpreter, perl
or perl.exe
:
perl helloworld.pl [arg0 [arg1 [arg2 ...]]]
A few immediate notes. Perl's syntax is highly permissive and it will allow you to do things which result in ambiguous-looking statements with unpredictable behaviour. There's no point in me explaining what these behaviours are, because you want to avoid them. The way to avoid them is to put use strict; use warnings;
at the very top of every Perl script or module that you create. Statements of the form use foo;
are pragmas. A pragma is a signal to perl.exe
, which takes effect when initial syntactic validation is being performed, before the program starts running. These lines have no effect when the interpreter encounters them at run time.
The symbol #
begins a comment. A comment lasts until the end of the line. Perl has no block comment syntax.
Perl variables come in three types: scalars, arrays and hashes. Each type has its own sigil: $
, @
and %
respectively. Variables are declared using my
, and remain in scope until the end of the enclosing block or file.
A scalar variable can contain:
undef
(corresponds to None
in Python, null
in PHP)my $undef = undef; print $undef; # prints the empty string "" and raises a warning # implicit undef: my $undef2; print $undef2; # prints "" and raises exactly the same warning
my $num = 4040.5; print $num; # "4040.5"
my $string = "world"; print $string; # "world"
(References are coming up shortly.)
String concatenation using the .
operator (same as PHP):
print "Hello ".$string; # "Hello world"
Perl has no boolean data type. A scalar in an if
statement evaluates to boolean "false" if and only if it is one of the following:
undef
0
""
"0"
.The Perl documentation repeatedly claims that functions return "true" or "false" values in certain situations. In practice, when a function is claimed to return "true" it usually returns 1
, and when it is claimed to return false it usually returns the empty string, ""
.
It is impossible to determine whether a scalar contains a "number" or a "string". More precisely, it should never be necessary to do this. Whether a scalar behaves like a number or a string depends on the operator with which it is used. When used as a string, a scalar will behave like a string. When used as a number, a scalar will behave like a number (raising a warning if this isn't possible):
my $str1 = "4G"; my $str2 = "4H"; print $str1 . $str2; # "4G4H" print $str1 + $str2; # "8" with two warnings print $str1 eq $str2; # "" (empty string, i.e. false) print $str1 == $str2; # "1" with two warnings # The classic error print "yes" == "no"; # "1" with two warnings; both values evaluate to 0 when used as numbers
The lesson is to always using the correct operator in the correct situation. There are separate operators for comparing scalars as numbers and comparing scalars as strings:
# Numerical operators: <, >, <=, >=, ==, !=, <=>, +, * # String operators: lt, gt, le, ge, eq, ne, cmp, ., x
An array variable is a list of scalars indexed by integers beginning at 0. In Python this is known as a list, and in PHP this is known as an array. An array is declared using a parenthesised list of scalars:
my @array = ( "print", "these", "strings", "out", "for", "me", # trailing comma is okay );
You have to use a dollar sign to access a value from an array, because the value being retrieved is not an array but a scalar:
print $array[0]; # "print" print $array[1]; # "these" print $array[2]; # "strings" print $array[3]; # "out" print $array[4]; # "for" print $array[5]; # "me" print $array[6]; # returns undef, prints "" and raises a warning
You can use negative indices to retrieve entries starting from the end and working backwards:
print $array[-1]; # "me" print $array[-2]; # "for" print $array[-3]; # "out" print $array[-4]; # "strings" print $array[-5]; # "these" print $array[-6]; # "print" print $array[-7]; # returns undef, prints "" and raises a warning
There is no collision between a scalar $var
and an array @var
containing a scalar entry $var[0]
. There may, however, be reader confusion, so avoid this.
To get an array's length:
print "This array has ".(scalar @array)."elements"; # "This array has 6 elements" print "The last populated index is ".$#array; # "The last populated index is 5"
The arguments with which the original Perl script was invoked are stored in the built-in array variable @ARGV
.
Variables can be interpolated into strings:
print "Hello $string"; # "Hello world" print "@array"; # "print these strings out for me"
Caution. One day you will put somebody's email address inside a string<EMAIL_ADDRESS>. This will cause Perl to look for an array variable called @gmail
to interpolate into the string, and not find it, resulting in a runtime error. Interpolation can be prevented in two ways: by backslash-escaping the sigil, or by using single quotes instead of double quotes.
print "Hello \$string"; # "Hello $string" print 'Hello $string'; # "Hello $string" print "\@array"; # "@array" print '@array'; # "@array"
A hash variable is a list of scalars indexed by strings. In Python this is known as a dictionary, and in PHP it is known as an array.
my %scientists = ( "Newton" => "Isaac", "Einstein" => "Albert", "Darwin" => "Charles", );
Notice how similar this declaration is to an array declaration. In fact, the double arrow symbol =>
is called a "fat comma", because it is just a synonym for the comma separator. A hash is declared using a list with an even number of elements, where the even-numbered elements (0, 2, ...) are all taken as strings.
Once again, you have to use a dollar sign to access a value from a hash, because the value being retrieved is not a hash but a scalar:
print $scientists{"Newton"}; # "Isaac" print $scientists{"Einstein"}; # "Albert" print $scientists{"Darwin"}; # "Charles" print $scientists{"Dyson"}; # returns undef, prints "" and raises a warning
Note the braces used here. Again, there is no collision between a scalar $var
and a hash %var
containing a scalar entry $var{"foo"}
.
You can convert a hash straight to an array with twice as many entries, alternating between key and value (and the reverse is equally easy):
my @scientists = %scientists;
However, unlike an array, the keys of a hash have no underlying order. They will be returned in whatever order is more efficient. So, notice the rearranged order but preserved pairs in the resulting array:
print "@scientists"; # something like "Einstein Albert Darwin Charles Newton Isaac"
To recap, you have to use square brackets to retrieve a value from an array, but you have to use braces to retrieve a value from a hash. The square brackets are effectively a numerical operator and the braces are effectively a string operator. The fact that the index supplied is a number or a string is of absolutely no significance:
my $data = "orange"; my @data = ("purple"); my %data = ( "0" => "blue"); print $data; # "orange" print $data[0]; # "purple" print $data["0"]; # "purple" print $data{0}; # "blue" print $data{"0"}; # "blue"
A list in Perl is a different thing again from either an array or a hash. You've just seen several lists:
( "print", "these", "strings", "out", "for", "me", ) ( "Newton" => "Isaac", "Einstein" => "Albert", "Darwin" => "Charles", )
A list is not a variable. A list is an ephemeral value which can be assigned to an array or a hash variable. This is why the syntax for declaring array and hash variables is identical. There are many situations where the terms "list" and "array" can be used interchangeably, but there are equally many where lists and arrays display subtly different and extremely confusing behaviour.
Okay. Remember that =>
is just ,
in disguise and then look at this example:
("one", 1, "three", 3, "five", 5) ("one" => 1, "three" => 3, "five" => 5)
The use of =>
hints that one of these lists is an array declaration and the other is a hash declaration. But on their own, neither of them are declarations of anything. They are just lists. Identical lists. Also:
()
There aren't even hints here. This list could be used to declare an empty array or an empty hash and the perl
interpreter clearly has no way of telling either way. Once you understand this odd aspect of Perl, you will also understand why the following fact must be true: List values cannot be nested. Try it:
my @array = ( "apples", "bananas", ( "inner", "list", "several", "entries", ), "cherries", );
Perl has no way of knowing whether ("inner", "list", "several", "entries")
is supposed to be an inner array or an inner hash. Therefore, Perl assumes that it is neither and flattens the list out into a single long list:
print $array[0]; # "apples" print $array[1]; # "bananas" print $array[2]; # "inner" print $array[3]; # "list" print $array[4]; # "several" print $array[5]; # "entries" print $array[6]; # "cherries"
The same is true whether the fat comma is used or not:
my %hash = ( "beer" => "good", "bananas" => ( "green" => "wait", "yellow" => "eat", ), ); # The above raises a warning because the hash was declared using a 7-element list print $hash{"beer"}; # "good" print $hash{"bananas"}; # "green" print $hash{"wait"}; # "yellow"; print $hash{"eat"}; # undef, so prints "" and raises a warning
Of course, this does make it easy to concatenate multiple arrays together:
my @bones = ("humerus", ("jaw", "skull"), "tibia"); my @fingers = ("thumb", "index", "middle", "ring", "little"); my @parts = (@bones, @fingers, ("foot", "toes"), "eyeball", "knuckle"); print @parts;
More on this shortly.
Perl's most distinctive feature is that its code is context-sensitive. Every expression in Perl is evaluated either in scalar context or list context, depending on whether it is expected to produce a scalar or a list. Many Perl expressions and built-in functions display radically different behaviour depending on the context in which they are evaluated.
A scalar assignment such as $scalar =
evaluates its expression in scalar context. In this case, the expression is "Mendeleev"
and the returned value is the same scalar value "Mendeleev"
:
my $scalar = "Mendeleev";
An array or hash assignment such as @array =
or %hash =
evaluates its expression in list context. A list value evaluated in list context returns the list, which then gets fed in to populate the array or hash:
my @array = ("Alpha", "Beta", "Gamma", "Pie"); my %hash = ("Alpha" => "Beta", "Gamma" => "Pie");
No surprises so far.
A scalar expression evaluated in list context turns into a single-element list:
my @array = "Mendeleev"; # same as 'my @array = ("Mendeleev");'
A list expression evaluated in scalar context returns the final scalar in the list:
my $scalar = ("Alpha", "Beta", "Gamma", "Pie"); # Value of $scalar is now "Pie"
An array expression (an array is different from a list, remember?) evaluated in scalar context returns the length of the array:
my @array = ("Alpha", "Beta", "Gamma", "Pie"); my $scalar = @array; # Value of $scalar is now 4
The print
built-in function evaluates all of its arguments in list context. In fact, print
accepts an unlimited list of arguments and prints each one after the other, which means it can be used to print arrays directly:
my @array = ("Alpha", "Beta", "Goo"); my $scalar = "-X-"; print @array; # "AlphaBetaGoo"; print $scalar, @array, 98; # "-X-AlphaBetaGoo98";
You can force any expression to be evaluated in scalar context using the scalar
built-in function. In fact, this is why we use scalar
to retrieve the length of an array.
You are not bound by law or syntax to return a scalar value when a subroutine is evaluated in scalar context, nor to return a list value in list context. As seen above, Perl is perfectly capable of fudging the result for you.
In the same way that lists cannot contain lists as elements, arrays and hashes cannot contain other arrays and hashes as elements. They can only contain scalars. Watch what happens when we try:
my @outer = ("Sun", "Mercury", "Venus", undef, "Mars"); my @inner = ("Earth", "Moon"); $outer[3] = @inner; print $outer[3]; # "2"
$outer[3]
is a scalar, so it demands a scalar value. When you try to assign an array value like @inner
to it, @inner
is evaluated in scalar context. This is the same as assigning scalar @inner
, which is the length of array @inner
, which is 2.
However, a scalar variable may contain a reference to any variable, including an array variable or a hash variable. This is how more complicated data structures are created in Perl.
A reference is created using a backslash.
my $colour = "Indigo"; my $scalarRef = \$colour;
Any time you would use the name of a variable, you can instead just put some braces in, and, within the braces, put a reference to a variable instead.
print $colour; # "Indigo" print $scalarRef; # e.g. "SCALAR(0x182c180)" print ${ $scalarRef }; # "Indigo"
As long as the result is not ambiguous, you can omit the braces too:
print $$scalarRef; # "Indigo"
If your reference is a reference to an array or hash variable, you can get data out of it using braces or using the more popular arrow operator, ->
:
my @colours = ("Red", "Orange", "Yellow", "Green", "Blue"); my $arrayRef = \@colours; print $colours[0]; # direct array access print ${ $arrayRef }[0]; # use the reference to get to the array print $arrayRef->[0]; # exactly the same thing my %atomicWeights = ("Hydrogen" => 1.008, "Helium" => 4.003, "Manganese" => 54.94); my $hashRef = \%atomicWeights; print $atomicWeights{"Helium"}; # direct hash access print ${ $hashRef }{"Helium"}; # use a reference to get to the hash print $hashRef->{"Helium"}; # exactly the same thing - this is very common
Here are four examples, but in practice the last one is the most useful.
my %owner1 = ( "name" => "Santa Claus", "DOB" => "1882-12-25", ); my $owner1Ref = \%owner1; my %owner2 = ( "name" => "Mickey Mouse", "DOB" => "1928-11-18", ); my $owner2Ref = \%owner2; my @owners = ( $owner1Ref, $owner2Ref ); my $ownersRef = \@owners; my %account = ( "number" => "12345678", "opened" => "2000-01-01", "owners" => $ownersRef, );
That's obviously unnecessarily laborious, because you can shorten it to:
my %owner1 = ( "name" => "Santa Claus", "DOB" => "1882-12-25", ); my %owner2 = ( "name" => "Mickey Mouse", "DOB" => "1928-11-18", ); my @owners = ( \%owner1, \%owner2 ); my %account = ( "number" => "12345678", "opened" => "2000-01-01", "owners" => \@owners, );
It is also possible to declare anonymous arrays and hashes using different symbols. Use square brackets for an anonymous array and braces for an anonymous hash. The value returned in each case is a reference to the anonymous data structure in question. Watch carefully, this results in exactly the same %account
as above:
# Braces denote an anonymous hash my $owner1Ref = { "name" => "Santa Claus", "DOB" => "1882-12-25", }; my $owner2Ref = { "name" => "Mickey Mouse", "DOB" => "1928-11-18", }; # Square brackets denote an anonymous array my $ownersRef = [ $owner1Ref, $owner2Ref ]; my %account = ( "number" => "12345678", "opened" => "2000-01-01", "owners" => $ownersRef, );
Or, for short (and this is the form you should actually use when declaring complex data structures in-line):
my %account = ( "number" => "31415926", "opened" => "3000-01-01", "owners" => [ { "name" => "Philip Fry", "DOB" => "1974-08-06", }, { "name" => "Hubert Farnsworth", "DOB" => "2841-04-09", }, ], );
Now, let's assume that you still have %account
kicking around but everything else (if there was anything else) has fallen out of scope. You can print the information out by reversing the same procedure in each case. Again, here are four examples, of which the last is the most useful:
my $ownersRef = $account{"owners"}; my @owners = @{ $ownersRef }; my $owner1Ref = $owners[0]; my %owner1 = %{ $owner1Ref }; my $owner2Ref = $owners[1]; my %owner2 = %{ $owner2Ref }; print "Account #", $account{"number"}, "\n"; print "Opened on ", $account{"opened"}, "\n"; print "Joint owners:\n"; print "\t", $owner1{"name"}, " (born ", $owner1{"DOB"}, ")\n"; print "\t", $owner2{"name"}, " (born ", $owner2{"DOB"}, ")\n";
Or, for short:
my @owners = @{ $account{"owners"} }; my %owner1 = %{ $owners[0] }; my %owner2 = %{ $owners[1] }; print "Account #", $account{"number"}, "\n"; print "Opened on ", $account{"opened"}, "\n"; print "Joint owners:\n"; print "\t", $owner1{"name"}, " (born ", $owner1{"DOB"}, ")\n"; print "\t", $owner2{"name"}, " (born ", $owner2{"DOB"}, ")\n";
Or using references and the ->
operator:
my $ownersRef = $account{"owners"}; my $owner1Ref = $ownersRef->[0]; my $owner2Ref = $ownersRef->[1]; print "Account #", $account{"number"}, "\n"; print "Opened on ", $account{"opened"}, "\n"; print "Joint owners:\n"; print "\t", $owner1Ref->{"name"}, " (born ", $owner1Ref->{"DOB"}, ")\n"; print "\t", $owner2Ref->{"name"}, " (born ", $owner2Ref->{"DOB"}, ")\n";
And if we completely skip all the intermediate values:
print "Account #", $account{"number"}, "\n"; print "Opened on ", $account{"opened"}, "\n"; print "Joint owners:\n"; print "\t", $account{"owners"}->[0]->{"name"}, " (born ", $account{"owners"}->[0]->{"DOB"}, ")\n"; print "\t", $account{"owners"}->[1]->{"name"}, " (born ", $account{"owners"}->[1]->{"DOB"}, ")\n";
This array has five elements:
my @array1 = (1, 2, 3, 4, 5); print @array1; # "12345"
This array, however, has ONE element (which happens to be a reference to an anonymous, five-element array):
my @array2 = [1, 2, 3, 4, 5]; print @array2; # e.g. "ARRAY(0x182c180)"
This scalar is a reference to an anonymous, five-element array:
my $array3Ref = [1, 2, 3, 4, 5]; print $array3Ref; # e.g. "ARRAY(0x22710c0)" print @{ $array3Ref }; # "12345" print @$array3Ref; # "12345"
if
... elsif
... else
...No surprises here, other than the spelling of elsif
:
my $word = "antidisestablishmentarianism"; my $strlen = length $word; if($strlen >= 15) { print "'", $word, "' is a very long word"; } elsif(10 <= $strlen && $strlen < 15) { print "'", $word, "' is a medium-length word"; } else { print "'", $word, "' is a a short word"; }
Perl provides a shorter "statement if
condition" syntax which is highly recommended for short statements:
print "'", $word, "' is actually enormous" if $strlen >= 20;
unless
... else
...my $temperature = 20; unless($temperature > 30) { print $temperature, " degrees Celsius is not very hot"; } else { print $temperature, " degrees Celsius is actually pretty hot"; }
unless
blocks are generally best avoided like the plague because they are very confusing. An "unless
[... else
]" block can be trivially refactored into an "if
[... else
]" block by negating the condition [or by keeping the condition and swapping the blocks]. Mercifully, there is no elsunless
keyword.
This, by comparison, is highly recommended because it is so easy to read:
print "Oh no it's too cold" unless $temperature > 15;
The ternary operator ?:
allows simple if
statements to be embedded in a statement. The canonical use for this is singular/plural forms:
my $gain = 48; print "You gained ", $gain, " ", ($gain == 1 ? "experience point" : "experience points"), "!";
Aside: singulars and plurals are best spelled out in full in both cases. Don't do something clever like the following, because anybody searching the codebase to replace the words "tooth" or "teeth" will never find this line:
my $lost = 1; print "You lost ", $lost, " t", ($lost == 1 ? "oo" : "ee"), "th!";
Ternary operators may be nested:
my $eggs = 5; print "You have ", $eggs == 0 ? "no eggs" : $eggs == 1 ? "an egg" : "some eggs";
if
statements evaluate their conditions in scalar context. For example, if(@array)
returns true if and only if @array
has 1 or more elements. It doesn't matter what those elements are - they may contain undef
or other false values for all we care.
There's More Than One Way To Do It.
Perl has a conventional while
loop:
my $i = 0; while($i < scalar @array) { print $i, ": ", $array[$i]; $i++; }
Perl also offers the until
keyword:
my $i = 0; until($i >= scalar @array) { print $i, ": ", $array[$i]; $i++; }
These do
loops are almost equivalent to the above (a warning would be raised if @array
were empty):
my $i = 0; do { print $i, ": ", $array[$i]; $i++; } while ($i < scalar @array);
and
my $i = 0; do { print $i, ": ", $array[$i]; $i++; } until ($i >= scalar @array);
Basic C-style for
loops are available too. Notice how we put a my
inside the for
statement, declaring $i
only for the scope of the loop:
for(my $i = 0; $i < scalar @array; $i++) { print $i, ": ", $array[$i]; } # $i has ceased to exist here, which is much tidier.
This kind of for
loop is considered old-fashioned and should be avoided where possible. Native iteration over a list is much nicer. Note: unlike PHP, the for
and foreach
keywords are synonyms. Just use whatever looks most readable:
foreach my $string ( @array ) { print $string; }
If you do need the indices, the range operator ..
creates an anonymous list of integers:
foreach my $i ( 0 .. $#array ) { print $i, ": ", $array[$i]; }
You can't iterate over a hash. However, you can iterate over its keys. Use the keys
built-in function to retrieve an array containing all the keys of a hash. Then use the foreach
approach that we used for arrays:
foreach my $key (keys %scientists) { print $key, ": ", $scientists{$key}; }
Since a hash has no underlying order, the keys may be returned in any order. Use the sort
built-in function to sort the array of keys alphabetically beforehand:
foreach my $key (sort keys %scientists) { print $key, ": ", $scientists{$key}; }
If you don't provide an explicit iterator, Perl uses a default iterator, $_
. $_
is the first and friendliest of the built-in variables:
foreach ( @array ) { print $_; }
If using the default iterator, and you only wish to put a single statement inside your loop, you can use the super-short loop syntax:
print $_ foreach @array;
next
and last
can be used to control the progress of a loop. In most programming languages these are known as continue
and break
respectively. We can also optionally provide a label for any loop. By convention, labels are written in ALLCAPITALS
. Having labelled the loop, next
and last
may target that label. This example finds primes below 100:
CANDIDATE: for my $candidate ( 2 .. 100 ) { for my $divisor ( 2 .. sqrt $candidate ) { next CANDIDATE if $candidate % $divisor == 0; } print $candidate." is prime\n"; }
We'll use @stack
to demonstrate these:
my @stack = ("Fred", "Eileen", "Denise", "Charlie"); print @stack; # "FredEileenDeniseCharlie"
pop
extracts and returns the final element of the array. This can be thought of as the top of the stack:
print pop @stack; # "Charlie" print @stack; # "FredEileenDenise"
push
appends extra elements to the end of the array:
push @stack, "Bob", "Alice"; print @stack; # "FredEileenDeniseBobAlice"
shift
extracts and returns the first element of the array:
print shift @stack; # "Fred" print @stack; # "EileenDeniseBobAlice"
unshift
inserts new elements at the beginning of the array:
unshift @stack, "Hank", "Grace"; print @stack; # "HankGraceEileenDeniseBobAlice"
pop
, push
, shift
and unshift
are all special cases of splice
. splice
removes and returns an array slice, replacing it with a different array slice:
print splice(@stack, 1, 4, "<<<", ">>>"); # "GraceEileenDeniseBob" print @stack; # "Hank<<<>>>Alice"
Perl provides the following functions which act on arrays to create other arrays.
The join
function concatenates many strings into one:
my @elements = ("Antimony", "Arsenic", "Aluminum", "Selenium"); print @elements; # "AntimonyArsenicAluminumSelenium" print "@elements"; # "Antimony Arsenic Aluminum Selenium" print join(", ", @elements); # "Antimony, Arsenic, Aluminum, Selenium"
In list context, the reverse
function returns a list in reverse order. In scalar context, reverse
concatenates the whole list together and then reverses it as a single word.
print reverse("Hello", "World"); # "WorldHello" print reverse("HelloWorld"); # "HelloWorld" print scalar reverse("HelloWorld"); # "dlroWolleH" print scalar reverse("Hello", "World"); # "dlroWolleH"
The map
function takes an array as input and applies an operation to every scalar $_
in this array. It then constructs a new array out of the results. The operation to perform is provided in the form of a single expression inside braces:
my @capitals = ("Baton Rouge", "Indianapolis", "Columbus", "Montgomery", "Helena", "Denver", "Boise"); print join ", ", map { uc $_ } @capitals; # "BATON ROUGE, INDIANAPOLIS, COLUMBUS, MONTGOMERY, HELENA, DENVER, BOISE"
The grep
function takes an array as input and returns a filtered array as output. The syntax is similar to map
. This time, the second argument is evaluated for each scalar $_
in the input array. If a boolean true value is returned, the scalar is put into the output array, otherwise not.
print join ", ", grep { length $_ == 6 } @capitals; # "Helena, Denver"
Obviously, the length of the resulting array is the number of successful matches, which means you can use grep
to quickly check whether an array contains an element:
print scalar grep { $_ eq "Columbus" } @capitals; # "1"
grep
and map
may be combined to form list comprehensions, an exceptionally powerful feature conspicuously absent from many other programming languages.
By default, the sort
function returns the input array, sorted into lexical (alphabetical) order:
my @elevations = (19, 1, 2, 100, 3, 98, 100, 1056); print join ", ", sort @elevations; # "1, 100, 100, 1056, 19, 2, 3, 98"
However, similar to grep
and map
, you may supply some code of your own. Sorting is always performed using a series of comparisons between two elements. Your block receives $a
and $b
as inputs and should return -1 if $a
is "less than" $b
, 0 if they are "equal" or 1 if $a
is "greater than" $b
.
The cmp
operator does exactly this for strings:
print join ", ", sort { $a cmp $b } @elevations; # "1, 100, 100, 1056, 19, 2, 3, 98"
The "spaceship operator", <=>
, does the same for numbers:
print join ", ", sort { $a <=> $b } @elevations; # "1, 2, 3, 19, 98, 100, 100, 1056"
$a
and $b
are always scalars, but they can be references to quite complex objects which are difficult to compare. If you need more space for the comparison, you can create a separate subroutine and provide its name instead:
sub comparator { # lots of code... # return -1, 0 or 1 } print join ", ", sort comparator @elevations;
You can't do this for grep
or map
operations.
Notice how the subroutine and block are never explicitly provided with $a
and $b
. Like $_
, $a
and $b
are, in fact, global variables which are populated with a pair of values to be compared each time.
By now you have seen at least a dozen built-in functions: print
, sort
, map
, grep
, keys
, scalar
and so on. Built-in functions are one of Perl's greatest strengths. They
The best advice regarding built-in functions is to know that they exist. Skim the documentation for future reference. If you are carrying out a task which feels like it's low-level and common enough that it's been done many times before, the chances are that it has.
Subroutines are declared using the sub
keyword. In contrast with built-in functions, user-defined subroutines always accept the same input: a list of scalars. That list may of course have a single element, or be empty. A single scalar is taken as a list with a single element. A hash with N elements is taken as a list with 2N elements.
Although the brackets are optional, subroutines should always be invoked using brackets, even when called with no arguments. This makes it clear that a subroutine call is happening.
Once you're inside a subroutine, the arguments are available using the built-in array variable @_
. Example:
sub hyphenate { # Extract the first argument from the array, ignore everything else my $word = shift @_; # An overly clever list comprehension $word = join "-", map { substr $word, $_, 1 } (0 .. (length $word) - 1); return $word; } print hyphenate("exterminate"); # "e-x-t-e-r-m-i-n-a-t-e"
There's More Than One Way To unpack @_
, but some are superior to others.
The example subroutine left_pad
below pads a string out to the required length using the supplied pad character. (The x
function concatenates multiple copies of the same string in a row.) (Note: for brevity, these subroutines all lack some elementary error checking, i.e. ensuring the pad character is only 1 character, checking that the width is greater than or equal to the length of existing string, checking that all needed arguments were passed at all.)
left_pad
is typically invoked as follows:
print left_pad("hello", 10, "+"); # "+++++hello"
Some people don't unpack the arguments at all and use @_
"live". This is ugly and discouraged:
sub left_pad { my $newString = ($_[2] x ($_[1] - length $_[0])) . $_[0]; return $newString; }
Unpacking @_
is only slightly less strongly discouraged:
sub left_pad { my $oldString = $_[0]; my $width = $_[1]; my $padChar = $_[2]; my $newString = ($padChar x ($width - length $oldString)) . $oldString; return $newString; }
Unpacking @_
by removing data from it using shift
is recommended for up to 4 arguments:
sub left_pad { my $oldString = shift @_; my $width = shift @_; my $padChar = shift @_; my $newString = ($padChar x ($width - length $oldString)) . $oldString; return $newString; }
If no array is provided to the shift
function, then it operates on @_
implicitly. This approach is seen very commonly:
sub left_pad { my $oldString = shift; my $width = shift; my $padChar = shift; my $newString = ($padChar x ($width - length $oldString)) . $oldString; return $newString; }
Beyond 4 arguments it becomes hard to keep track of what is being assigned where.
You can unpack @_
all in one go using multiple simultaneous scalar assignment. Again, this is okay for up to 4 arguments:
sub left_pad { my ($oldString, $width, $padChar) = @_; my $newString = ($padChar x ($width - length $oldString)) . $oldString; return $newString; }
For subroutines with large numbers of arguments or where some arguments are optional or cannot be used in combination with others, best practice is to require the user to provide a hash of arguments when calling the subroutine, and then unpack @_
back into that hash of arguments. For this approach, our subroutine call would look a little different:
print left_pad("oldString" => "pod", "width" => 10, "padChar" => "+");
And the subroutine itself looks like this:
sub left_pad { my %args = @_; my $newString = ($args{"padChar"} x ($args{"width"} - length $args{"oldString"})) . $args{"oldString"}; return $newString; }
Like other Perl expressions, subroutine calls may display contextual behaviour. You can use the wantarray
function (which should be called wantlist
but never mind) to detect what context the subroutine is being evaluated in, and return a result appropriate to that context:
sub contextualSubroutine { # Caller wants a list. Return a list return ("Everest", "K2", "Etna") if wantarray; # Caller wants a scalar. Return a scalar return 3; } my @array = contextualSubroutine(); print @array; # "EverestK2Etna" my $scalar = contextualSubroutine(); print $scalar; # "3"
Apologies if you already know the following non-Perl-related facts. Every time a process finishes on a Windows or Linux system (and, I assume, on most other systems), it concludes with a 16-bit status word. The highest 8 bits constitute a return code between 0 and 255 inclusive, with 0 conventionally representing unqualified success, and other values representing various degrees of failure. The other 8 bits are less frequently examined - they "reflect mode of failure, like signal death and core dump information".
You can exit from a Perl script with the return code of your choice (from 0 to 255) using exit
.
Perl provides More Than One Way To - in a single call - spawn a child process, pause the current script until the child process has finished, and then resume interpretation of the current script. Whichever method is used, you will find that immediately afterwards, the built-in scalar variable $?
has been populated with the status word that was returned from that child process's termination. You can get the return code by taking just the highest 8 of those 16 bits: $? >> 8
.
The system
function can be used to invoke another program with the arguments listed. The value returned by system
is the same value with which $?
is populated:
my $rc = system "perl", "anotherscript.pl", "foo", "bar", "baz"; $rc >>= 8; print $rc; # "37"
Alternatively, you can use backticks ``
to run an actual command at the command line and capture the standard output from that command. In scalar context the entire output is returned as a single string. In list context, the entire output is returned as an array of strings, each one representing a line of output.
my $text = `perl anotherscript.pl foo bar baz`; print $text; # "foobarbaz"
This is the behaviour which would be seen if anotherscript.pl
contained, for example:
use strict; use warnings; print @ARGV; exit 37;
A scalar variable may contain a file handle instead of a number/string/reference or undef
. A file handle is essentially a reference to a specific location inside a specific file.
Use open
to turn a scalar variable into a file handle. open
must be supplied with a mode. The mode <
indicates that we wish to open the file to read from it:
my $f = "text.txt"; my $result = open my $fh, "<", $f; if(!$result) { die "Couldn't open '".$f."' for reading because: ".$!; }
If successful, open
returns a true value. Otherwise, it returns false and an error message is stuffed into the built-in variable $!
. As seen above, you should always check that the open
operation completed successfully. This checking being rather tedious, a common idiom is:
open(my $fh, "<", $f) || die "Couldn't open '".$f."' for reading because: ".$!;
Note the need for parentheses around the open
call's arguments.
To read a line of text from a filehandle, use the readline
built-in function. readline
returns a full line of text, with a line break intact at the end of it (except possibly for the final line of the file), or undef
if you've reached the end of the file.
while(1) { my $line = readline $fh; last unless defined $line; # process the line... }
To truncate that possible trailing line break, use chomp
:
chomp $line;
Note that chomp
acts on $line
in place. $line = chomp $line
is probably not what you want.
You can also use eof
to detect that the end of the file has been reached:
while(!eof $fh) { my $line = readline $fh; # process $line... }
But beware of just using while(my $line = readline $fh)
, because if $line
turns out to be "0"
, the loop will terminate early. If you want to write something like that, Perl provides the <>
operator which wraps up readline
in a fractionally safer way. This is very commonly-seen and perfectly safe:
while(my $line = <$fh>) { # process $line... }
And even:
while(<$fh>) { # process $_... }
Writing to a file involves first opening it in a different mode. The mode >
indicates that we wish to open the file to write to it. (>
will clobber the content of the target file if it already exists and has content. To merely append to an existing file, use mode >>
.) Then, simply provide the filehandle as a zeroth argument for the print
function.
open(my $fh2, ">", $f) || die "Couldn't open '".$f."' for writing because: ".$!; print $fh2 "The eagles have left the nest";
Notice the absence of a comma between $fh2
and the next argument.
File handles are actually closed automatically when they drop out of scope, but otherwise:
close $fh2; close $fh;
Three filehandles exist as global constants: STDIN
, STDOUT
and STDERR
. These are open automatically when the script starts. To read a single line of user input:
my $line = <STDIN>;
To just wait for the user to hit Enter:
<STDIN>;
Calling <>
with no filehandle reads data from STDIN
, or from any files named in arguments when the Perl script was called.
As you may have gathered, print
prints to STDOUT
by default if no filehandle is named.
The function -e
is a built-in function which tests whether the named file exists.
print "what" unless -e "/usr/bin/perl";
The function -d
is a built-in function which tests whether the named file is a directory.
The function -f
is a built-in function which tests whether the named file is a plain file.
These are just three of a large class of functions of the form -X
where X
is some lower- or upper-case letter. These functions are called file tests. Note the leading minus sign. In a Google query, the minus sign indicates to exclude results containing this search term. This makes file tests hard to Google for! Just search for "perl file test" instead.
Regular expressions appear in many languages and tools other than Perl. Perl's core regular expression syntax is basically the same as everywhere else, but Perl's full regular expression capabilities are terrifyingly complex and difficult to understand. The best advice I can give you is to avoid this complexity wherever possible.
Match operations are performed using =~ m//
. In scalar context, =~ m//
returns true on success, false on failure.
my $string = "Hello world"; if($string =~ m/(\w+)\s+(\w+)/) { print "success"; }
Parentheses perform sub-matches. After a successful match operation is performed, the sub-matches get stuffed into the built-in variables $1
, $2
, $3
, ...:
print $1; # "Hello" print $2; # "world"
In list context, =~ m//
returns $1
, $2
, ... as a list.
my $string = "colourless green ideas sleep furiously"; my @matches = $string =~ m/(\w+)\s+((\w+)\s+(\w+))\s+(\w+)\s+(\w+)/; print join ", ", map { "'".$_."'" } @matches; # prints "'colourless', 'green ideas', 'green', 'ideas', 'sleep', 'furiously'"
Substitution operations are performed using =~ s///
.
my $string = "Good morning world"; $string =~ s/world/Vietnam/; print $string; # "Good morning Vietnam"
Notice how the contents of $string
have changed. You have to pass a scalar variable on the left-hand side of an =~ s///
operation. If you pass a literal string, you'll get an error.
The /g
flag indicates "group match".
In scalar context, each =~ m//g
call finds another match after the previous one, returning true on success, false on failure. You can access $1
and so on afterwards in the usual way. For example:
my $string = "a tonne of feathers or a tonne of bricks"; while($string =~ m/(\w+)/g) { print "'".$1."'\n"; }
In list context, an =~ m//g
call returns all of the matches at once.
my @matches = $string =~ m/(\w+)/g; print join ", ", map { "'".$_."'" } @matches;
An =~ s///g
call performs a global search/replace and returns the number of matches. Here, we replace all vowels with the letter "r".
# Try once without /g. $string =~ s/[aeiou]/r/; print $string; # "r tonne of feathers or a tonne of bricks" # Once more. $string =~ s/[aeiou]/r/; print $string; # "r trnne of feathers or a tonne of bricks" # And do all the rest using /g $string =~ s/[aeiou]/r/g; print $string, "\n"; # "r trnnr rf frrthrrs rr r trnnr rf brrcks"
The /i
flag makes matches and substitutions case-insensitive.
The /x
flag allows your regular expression to contain whitespace (e.g., line breaks) and comments.
"Hello world" =~ m/ (\w+) # one or more word characters [ ] # single literal space, stored inside a character class world # literal "world" /x; # returns true
In Perl, modules and packages are different things.
A module is a .pm
file that you can include in another Perl file (script or module). A module is a text file with exactly the same syntax as a .pl
Perl script. An example module might be located at C:\foo\bar\baz\Demo\StringUtils.pm
or /foo/bar/baz/Demo/StringUtils.pm
, and read as follows:
use strict; use warnings; sub zombify { my $word = shift @_; $word =~ s/[aeiou]/r/g; return $word; } return 1;
Because a module is executed from top to bottom when it is loaded, you need to return a true value at the end to show that it was loaded successfully.
So that the Perl interpreter can find them, directories containing Perl modules should be listed in your environment variable PERL5LIB
before calling perl
. List the root directory containing the modules, don't list the module directories or the modules themselves:
set PERL5LIB=C:\foo\bar\baz;%PERL5LIB%
or
export PERL5LIB=/foo/bar/baz:$PERL5LIB
Once the Perl module is created and perl
knows where to look for it, you can use the require
built-in function to search for and execute it during a Perl script. For example, calling require Demo::StringUtils
causes the Perl interpreter to search each directory listed in PERL5LIB
in turn, looking for a file called Demo/StringUtils.pm
. After the module has been executed, the subroutines that were defined there suddenly become available to the main script. Our example script might be called main.pl
and read as follows:
use strict; use warnings; require Demo::StringUtils; print zombify("i want brains"); # "r wrnt brrrns"
Note the use of the double colon ::
as a directory separator.
Now a problem surfaces: if main.pl
contains many require
calls, and each of the modules so loaded contains more require
calls, then it can become difficult to track down the original declaration of the zombify()
subroutine. The solution to this problem is to use packages.
A package is a namespace in which subroutines can be declared. Any subroutine you declare is implicitly declared within the current package. At the beginning of execution, you are in the main
package, but you can switch package using the package
built-in function:
use strict; use warnings; sub subroutine { print "universe"; } package Food::Potatoes; # no collision: sub subroutine { print "kingedward"; }
Note the use of the double colon ::
as a namespace separator.
Any time you call a subroutine, you implicitly call a subroutine which is inside the current package. Alternatively, you can explicitly provide a package. See what happens if we continue the above script:
subroutine(); # "kingedward" main::subroutine(); # "universe" Food::Potatoes::subroutine(); # "kingedward"
So the logical solution to the problem described above is to modify C:\foo\bar\baz\Demo\StringUtils.pm
or /foo/bar/baz/Demo/StringUtils.pm
to read:
use strict; use warnings; package Demo::StringUtils; sub zombify { my $word = shift @_; $word =~ s/[aeiou]/r/g; return $word; } return 1;
And modify main.pl
to read:
use strict; use warnings; require Demo::StringUtils; print Demo::StringUtils::zombify("i want brains"); # "r wrnt brrrns"
Now read this next bit carefully.
Packages and modules are two completely separate and distinct features of the Perl programming language. The fact that they both use the same double colon delimiter is a huge red herring. It is possible to switch packages multiple times over the course of a script or module, and it is possible to use the same package declaration in multiple locations in multiple files. Calling require Foo::Bar
does not look for and load a file with a package Foo::Bar
declaration somewhere inside it, nor does it necessarily load subroutines in the Foo::Bar
namespace. Calling require Foo::Bar
merely loads a file called Foo/Bar.pm
, which need not have any kind of package declaration inside it at all, and in fact might declare package Baz::Qux
and other nonsense inside it for all you know.
Likewise, a subroutine call Baz::Qux::processThis()
need not necessarily have been declared inside a file named Baz/Qux.pm
. It could have been declared literally anywhere.
Separating these two concepts is one of the stupidest features of Perl, and treating them as separate concepts invariably results in chaotic, maddening code. Fortunately for us, the majority of Perl programmers obey the following two laws:
.pl
file) must always contain exactly zero package
declarations..pm
file) must always contain exactly one package
declaration, corresponding exactly to its name and location. E.g. module Demo/StringUtils.pm
must begin with package Demo::StringUtils
.Because of this, in practice you will find that most "packages" and "modules" produced by reliable third parties can be regarded and referred to interchangeably. However, it is important that you do not take this for granted, because one day you will meet code produced by a madman.
Perl is not a great language for OO programming. Perl's OO capabilities were grafted on after the fact, and this shows.
An object is simply a reference (i.e. a scalar variable) which happens to know which class its referent belongs to. To tell a reference that its referent belongs to a class, use bless
. To find out what class a reference's referent belongs to (if any), use ref
.
A method is simply a subroutine that expects an object (or, in the case of class methods, a package name) as its first argument. Object methods are invoked using $obj->method()
; class methods are invoked using Package::Name->method()
.
A class is simply a package that happens to contain methods.
A quick example makes this clearer. An example module Animal.pm
containing a class Animal
reads like this:
use strict; use warnings; package Animal; sub eat { # First argument is always the object to act upon. my $self = shift @_; foreach my $food ( @_ ) { if($self->can_eat($food)) { print "Eating ", $food; } else { print "Can't eat ", $food; } } } # For the sake of argument, assume an Animal can eat anything. sub can_eat { return 1; } return 1;
And we might make use of this class like so:
require Animal; my $animal = { "legs" => 4, "colour" => "brown", }; # $animal is an ordinary hash reference print ref $animal; # "HASH" bless $animal, "Animal"; # now it is an object of class "Animal" print ref $animal; # "Animal"
Note: literally any reference can be blessed into any class. It's up to you to ensure that (1) the referent can actually be used as an instance of this class and (2) that the class in question exists and has been loaded.
You can still work with the original hash in the usual way:
print "Animal has ", $animal->{"legs"}, " leg(s)";
But you can now also call methods on the object using the same ->
operator, like so:
$animal->eat("insects", "curry", "eucalyptus");
This final call is equivalent to Animal::eat($animal, "insects", "curry", "eucalyptus")
.
A constructor is a class method which returns a new object. If you want one, just declare one. You can use any name you like. For class methods, the first argument passed is not an object but a class name. In this case, "Animal"
:
use strict; use warnings; package Animal; sub new { my $class = shift @_; return bless { "legs" => 4, "colour" => "brown" }, $class; } # ...etc.
And then use it like so:
my $animal = Animal->new();
To create a class inheriting from a parent class, use use parent
. Let's suppose we subclassed Animal
with Koala
, located at Koala.pm
:
use strict; use warnings; package Koala; # Inherit from Animal use parent ("Animal"); # Override one method sub can_eat { my $self = shift @_; # Not used. You could just put "shift @_;" here my $food = shift @_; return $food eq "eucalyptus"; } return 1;
And some sample code:
use strict; use warnings; require Koala; my $koala = Koala->new(); $koala->eat("insects", "curry", "eucalyptus"); # eat only the eucalyptus
This final method call tries to invoke Koala::eat($koala, "insects", "curry", "eucalyptus")
, but a subroutine eat()
isn't defined in the Koala
package. However, because Koala
has a parent class Animal
, the Perl interpreter tries calling Animal::eat($koala, "insects", "curry", "eucalyptus")
instead, which works. Note how the class Animal
was loaded automatically by Koala.pm
.
Since use parent
accepts a list of parent class names, Perl supports multiple inheritance, with all the benefits and horrors this entails.
BEGIN
blocksA BEGIN
block is executed as soon as perl
has finished parsing that block, even before it parses the rest of the file. It is ignored at execution time:
use strict; use warnings; print "This gets printed second"; BEGIN { print "This gets printed first"; } print "This gets printed third";
A BEGIN
block is always executed first. If you create multiple BEGIN
blocks (don't), they are executed in order from top to bottom as the compiler encounters them. A BEGIN
block always executes first even if it is placed halfway through a script (don't do this) or at the end (or this). Do not mess with the natural order of code. Put BEGIN
blocks at the beginning!
A BEGIN
block is executed as soon as the block has been parsed. Once this is done, parsing resumes at the end of the BEGIN
block. Only once the whole script or module has been parsed is any of the code outside of BEGIN
blocks executed.
use strict; use warnings; print "This 'print' statement gets parsed successfully but never executed"; BEGIN { print "This gets printed first"; } print "This, also, is parsed successfully but never executed"; ...because e4h8v3oitv8h4o8gch3o84c3 there is a huge parsing error down here.
Because they are executed at compilation time, a BEGIN
block placed inside a conditional block will still be executed first, even if the conditional evaluates to false and despite the fact that the conditional has not been evaluated at all yet and in fact may never be evaluated.
if(0) { BEGIN { print "This will definitely get printed"; } print "Even though this won't"; }Do not put
BEGIN
blocks in conditionals! If you want to do something conditionally at compile time, you need to put the conditional inside the BEGIN
block:
BEGIN { if($condition) { # etc. } }
use
Okay. Now that you understand the obtuse behaviour and semantics of packages, modules, class methods and BEGIN
blocks, I can explain the exceedingly commonly-seen use
function.
The following three statements:
use Caterpillar ("crawl", "pupate"); use Caterpillar (); use Caterpillar;
are respectively equivalent to:
BEGIN { require Caterpillar; Caterpillar->import("crawl", "pupate"); } BEGIN { require Caterpillar; } BEGIN { require Caterpillar; Caterpillar->import(); }
use
call is a disguised BEGIN
block. The same warnings apply. use
statements must always be placed at the top of the file, and never inside conditionals.import()
is not a built-in Perl function. It is a user-defined class method. The burden is on the programmer of the Caterpillar
package to define or inherit import()
, and the method could theoretically accept anything as arguments and do anything with those arguments. use Caterpillar;
could do anything. Consult the documentation of Caterpillar.pm
to find out exactly what will happen.require Caterpillar
loads a module named Caterpillar.pm
, whereas Caterpillar->import()
calls the import()
subroutine that was defined inside the Caterpillar
package. Let's hope the module and the package coincide!The most common way to define an import()
method is to inherit it from the Exporter module. Exporter is a core module, and a de facto core feature of the Perl programming language. In Exporter's implementation of import()
, the list of arguments that you pass in is interpreted as a list of subroutine names. When a subroutine is import()
ed, it becomes available in the current package as well as in its own original package.
This concept is easiest to grasp using an example. Here's what Caterpillar.pm
looks like:
use strict; use warnings; package Caterpillar; # Inherit from Exporter use parent ("Exporter"); sub crawl { print "inch inch"; } sub eat { print "chomp chomp"; } sub pupate { print "bloop bloop"; } our @EXPORT_OK = ("crawl", "eat"); return 1;
The package variable @EXPORT_OK
should contain a list of subroutine names.
Another piece of code may then import()
these subroutines by name, typically using a use
statement:
use strict; use warnings; use Caterpillar ("crawl"); crawl(); # "inch inch"
In this case, the current package is main
, so the crawl()
call is actually a call to main::crawl()
, which (because it was imported) maps to Caterpillar::crawl()
.
Note: regardless of the content of @EXPORT_OK
, every method can always be called "longhand":
use strict; use warnings; use Caterpillar (); # no subroutines named, no import() call made # and yet... Caterpillar::crawl(); # "inch inch" Caterpillar::eat(); # "chomp chomp" Caterpillar::pupate(); # "bloop bloop"
Perl has no private methods. Customarily, a method intended for private use is named with a leading underscore or two.
@EXPORT
The Exporter module also defines a package variable called @EXPORT
, which can also be populated with a list of subroutine names.
use strict; use warnings; package Caterpillar; # Inherit from Exporter use parent ("Exporter"); sub crawl { print "inch inch"; } sub eat { print "chomp chomp"; } sub pupate { print "bloop bloop"; } our @EXPORT = ("crawl", "eat", "pupate"); return 1;
The subroutines named in @EXPORT
are exported if import()
is called with no arguments at all, which is what happens here:
use strict; use warnings; use Caterpillar; # calls import() with no arguments crawl(); # "inch inch" eat(); # "chomp chomp" pupate(); # "bloop bloop"
But notice how we are back in a situation where, without other clues, it might not be easy to tell where crawl()
was originally defined. The moral of this story is twofold:
When creating a module which makes use of Exporter, never use @EXPORT
to export subroutines by default. Always make the user call subroutines "longhand" or import()
them explicitly (using e.g. use Caterpillar ("crawl")
, which is a strong clue to look in Caterpillar.pm
for the definition of crawl()
).
When use
ing a module which makes use of Exporter, always explicitly name the subroutines you want to import()
. If you don't want to import()
any subroutines and wish to refer to them longhand, you must supply an explicit empty list: use Caterpillar ()
.
The core module Data::Dumper can be used to output an arbitrary scalar to the screen. This is an essential debug tool.
There's an alternate syntax, qw{ }
, for declaring arrays. This is often seen in use
statements:
use Account qw{create open close suspend delete};
There are many other quote-like operators.
In =~ m//
and =~ s///
operations, you can use braces instead of slashes as the regex delimiters. This is quite useful if your regex contains a lot of slashes, which would otherwise need escaping with backslashes. For example, =~ m{///}
matches three literal forward slashes, and =~ s{^https?://}{}
removes the protocol part of a URL.
Perl does have CONSTANTS
. These are discouraged now, but weren't always. Constants are actually just subroutine calls with omitted brackets.
Sometimes people omit quotes around hash keys, writing $hash{key}
instead of $hash{"key"}
. They can get away with it because in this situation the bareword key
occurs as the string "key"
, as opposed to a subroutine call key()
.
If you see a block of unformatted code wrapped in a delimiter with double chevrons, like <<EOF
, the magic word to Google for is "here-doc".
Warning! Many built-in functions can be called with no arguments, causing them to operate on $_
instead. Hopefully this will help you understand formations like:
print foreach @array;
and
foreach ( @array ) { next unless defined; }
I dislike this formation because it can lead to problems when refactoring.
The end.


Quickpool is a simple web application that makes it easier to create carpools based purely on user demand.
Built with Ruby on Rails and utilizes GeoKit and Twilio functionality.
GithubAn interactive and clickable version of JSON Pretty Print. Formats XML/JSON objects and generates the key path for any specific attribute you click.
Built with Ruby on Rails. Deployed on Heroku
GithubAn autonomous web application that graphically categorizes and displays all the bills approaching congressional debate ot vote in real-time.
Built with MongoDB and Nodejs. Deployed on Heroku.
GithubEmail: ctkochan22 (at) gmail.com
Phone:<PHONE_NUMBER>


Fengshui Yo' Life!
Welcome {{email}}!
Saved Results
FAQ
Logout
Submit
Results
My Chinese Year Sign
My Chinese Month Sign
My Allies
My Peach Blossom Animal
Save


Styra is the original creator of Open Policy
Agent and provides support, professional services, training, and
enterprise products.
Policy-as-Code Laboratories provides strategic planning
and integration consulting for OPA and Rego across the PaC ecosystem
(Cloud, Kubernetes, Open Shift and legacy platforms)


>
Click on the Twitter icon at the bottom of the page and authorise
The Block Bot to block on your behalf.
If you are having issues try
clearing your session.
Links:
More Information (Privacy/How it Works) &
Contact @
The_Block_Bot or
the A+ forum if you are
blocked and want to complain ... Or if you want to be a blocker and have access to add to the blocklist then ask and we'll add you, assuming you are not on the list!
There are three levels to choose from :-
→ Level 1 blocking: this blocks only the worst of the worst. These are the really nasty ones.
Both “sides” across the Deep Rifts™ will hopefully agree these need to be blocked.
Accounts that spam extremely abusive messages to people with the intent only of hurting them with not a hint of “disagreement”.
D0x’ers who want to drop information on fellow atheists in order to scare them off the internet or have real life effects on their well-being.
Stalkers that create sock-accounts to inject themselves into your time line to get a response from you or imposters pretending to be you.
→ Level 2 blocking: these are the abusive subset of anti-feminists, MRAs, or all-round assholes who think nothing of tweeting their much loved
photoshopped pictures, memes and other wonderful media directly into your timeline to get attention (Listen to Meee!!1!).
This level also includes the “parody” accounts, if you have better things to do with your life than “disagree” on Twitter with a parody of yourself that
seems to have suffered a frontal lobotomy.
Level 2 blocking includes all members of level 1.
→ Level 3 blocking: these are the merely annoying and irritating Twitterers who trot out the A+ arguments to avoid at a moment’s notice,
and show no signs of giving them up until you pry them from their cold, dead hands.
Given that is not a practical option, how about blocking them and avoiding tedious exchanges?
This is the 100% frozen peach option… These from time to time leap to level 1/2 so why take the risk?
Level 3 blocking includes all members of levels 1 and 2.


Take both maxillary and mandibular impressions with alginate or heavy body PVS.
Pour stone models. Trim/relieve models to remove irregular areas.
Take a PVS bite and submit your case.
Place lip ruler on the incisive papilla & record upper lip measurement, by looking at the numbers from eye level. (If measurement
is not possible due to the presence of teeth, place it at estimated height outside the mouth and measure on top
of the lip).
Find out the desired gum and tooth shade by using a vita shade guide.
Log into your account and place order online (If new to DENTCA you will need to register and create an account)
Print order Sheet and shipping label and ship everything to DENTCA.
Ready to place an order? Click here to go to our ordering page.
Want to learn more about the next step? Click here to go to the DENTCA-4 Temp page.


LogicWidgets
Synopsis
This library contains common macros that allow a variety of logic operations to be performed. They also allow logic components to be easily combined using the visual network editor. The normal alternative to this would be to write specific procedural code.
General Notes
It should be noted that these macros are not intended for the expression of essential application logic. If they were used in this way the system performance is unlikely to be acceptable. The macros are instead intended to help write small control routines and avoid the necessity of developing program code for these. Examples of these control routines include controlling the operation of a user interface and disconnecting certain areas of the network when they are not needed.
The logical terms, TRUE and FALSE, have the same meaning in this library as they do in the C programming language. A value is defined to be TRUE if it is not zero. Conversely a value is defined to be FALSE if it is zero. These conventions are used throughout this library.
Before the individual macros are examined the specific meaning of a 'trigger' should be noted. When the value of a network component is updated AVS/Express sends a signal to all the components linked to it indicating that it has been updated. This is called a trigger signal. A trigger is sent whenever a value is updated with either a different value or the same value. Normally the trigger signal is used to notify other modules that new data is available. However it can be used to simply signify that something has happened. This is now the parse_v module uses its trigger input. Whenever a signal is recieved on the trigger input the parse_v module processes the supplied v code.
Most of the macros in this library generate trigger outputs by examining certain inputs and determining whether a criteria is TRUE or FALSE. These outputs can be used to trigger several modules. These include parse_v, copy_on_change, BreakableLink, ToggleableLink and several of the Database macros.
There are a range of macros in the LogicWidgets library that all begin with the If phrase. All of these macros implement forms of the programming structure if...then...else. The purpose of this structure is to test a certain criteria to determine if it is true or false and perform one of two actions depending on this. These macros implement this structure through the use of triggers. If the criteria is TRUE then the true output is triggered else the false output is triggered.
The If... macros can be separated into two catergories; those with a single logic input and those with two logic inputs. The macros with a single logic input provide general logical behaviour, whilst those with two logic inputs provide higher level and more specific behaviour.
The IfTrue macro is the simplest of the If... macros. It is a wrapper around the TrueFalseCore module and does not provide any extra functionality. It tests the input value and triggers the appropriate output. Therefore the true output is triggered if the input is non-zero and the false output is triggered if it is zero. This behaviour is of limited use itself. However more complex logical statements can be expressed by using the v-code logical and arithmetic operators. A statement such as this can be used as the input to the IfTrue macro. AVS/Express evaluates the statement to a single value which is them tested by the IfTrue macro.
A similar approach of using v-code statements combined with the low-level TrueFalseCore module is used in all the others If... macros. The most basic of these enhancements is the IfFalse macro. This provides the inverse behaviour of the IfTrue macro. If the input value is FALSE the true output is triggered. Otherwise the input value is TRUE and the false output is triggered.
All of the above macros have two logical inputs. The macros perform a wide variety of different tests on the inputs. The simplest of these tests is implemented by the IfEqualTo macro. This macro tests if the input numbers are numerically equal. If they are the true output is triggered, otherwise the false output is triggered. All the other macros derive from the IfEqualTo macro and alter it to provide a variety of different tests. The exact definition of these tests is shown in the table below.
Inputs
&trigger
This integer parameter is a trigger input that is present on the IfTrue and IfFalse macros. When this parameter is triggered the value on the input of the module is evaluated and the appropriate outputs triggered. Changing the input itself also causes the input to be evaluated. However it is possible to cause the module to retrigger without altering its state by using this input. An example of its use can be seen in the Toggle macro. This trigger input is also available on the other macros however it is not directly exposed as an input.
&in &in1 &in2
These integer parameter are the input parameters to the If... macros. The IfTrue and IfFalse macros use the single input in, whilst the two inputs macros use the inputs in1 and in2. These inputs are evaluated by the macros to determine which output should be triggered.
Outputs
cond
This integer parameter is used to output the evaluated state of the input. In logical terms this parameter will have the same value as the input criteria. However it is restricted to a true binary representation of 0 and 1 only. Therefore if the input criteria is TRUE a 1 is output, otherwise a 0 is output. This parameter is triggered whenever the input is changed.
cond_true
This integer parameter is triggered whenever the input condition evaluates to TRUE. The actual value of this parameter is not significant and it should not be accessed.
state_false
This integer parameter is triggered whenever the the input condition evaluates to FALSE. The actual value of this parameter is not significant and it should not be accessed.
Truth Table
This table is intended to describe exactly how these macros will behave in logical terms. It uses the same logic operators as the v language uses.
| Macro Name |
cond_true triggered |
cond_false triggered |
| IfTrue |
in != 0 |
in == 0 |
| IfFalse |
in == 0 |
in != 0 |
| IfEqualTo |
in1 == in2 |
in1 != in2 |
| IfNotEqualTo |
in1 != in2 |
in1 == in2 |
| IfLessThan |
in1 < in2 |
in1 >= in2 |
| IfGreaterThan |
in1 > in2 |
in1 <= in2 |
| IfLessThanEqual |
in1 <= in2 |
in1 > in2 |
| IfGreaterThanEqual |
in1 >= in2 |
in1 < in2 |
| IfLogicalAND |
in1 && in2 |
!(in1 && in2) |
| IfLogicalOR |
in1 || in2 |
!(in1 || in2) |
| IfBitwiseAND |
(in1 & in2) != 0 |
(in1 & in2) == 0 |
| IfBitwiseOR |
(in1 | in2) != 0 |
(in1 | in2) == 0 |
This macro stores a value that can be toggled between TRUE and FALSE through the use of a single trigger input. Whenever a trigger is received on the macro input the state of the stored value is tested. If the stored value is TRUE then the stored value is set to 0, and therefore FALSE. Conversely if the stored value is FALSE then the stored value is set to 1, and therefore TRUE. The macro also has trigger outputs. The Toggle macro can be used for a variety of tasks,
in particular it should be useful for storing the results of a trigger output.
Inputs
&trigger
This integer trigger parameter is used to toggle the state of the stored value. Whenever this parameter is triggered the stored value is changed from 0 to 1 or from 1 to 0 as appropriate.
Outputs
out
The state of the toggle.
not_out
The inverse of the state of the toggle.
value_true
This integer parameter is triggered whenever the toggle state is changed from 0 to 1. The actual value of this parameter is not significant and it should not be accessed.
value_false
This integer parameter is triggered whenever the toggle state is changed from 1 to 0. The actual value of this parameter is not significant and it should not be accessed.
This macro stores a value that can be switched between TRUE and FALSE throught the use of two trigger inputs. Whenever a trigger is received on the on macro input the state of the stored value is switched to TRUE. Conversely whenever a trigger is received on the off macro input the state of the stored value is switched to FALSE.
Inputs
&on
This integer trigger parameter is used to switch the state of the stored value to TRUE.
&off
This integer trigger parameter is used to switch the state of the stored value to FALSE.
Outputs
out
The state of the switch.
The parse_v_on... range of macros all allow v code statements to be executed whenever a set criteria is TRUE. They combine the standard parse_v module with the TrueFalseCore module. The TrueFalseCore module tests the supplied values to determine if they meet the set criteria. If they do the TrueFalseCore module triggers the parse_v module to process the set v code statements. The parse_v module can be used in exactly the way that it is used normally.
As with the If... macros the parse_v_on... macros can be spilt into two catergories; single and double input macros. Boardly the logical criteria of each of the parse_v_on... macros corresponds with the respective If... macros. However the parse_v_on... macros do not implement as many criteria as the If... macros. This is not a limitation of the system. The extra macros are not present so that the number of macros in the LogicWidgets library could be keep to an acceptable number. If the extra criteria are required the parse_v_on_equal macro can be easily used as the basis of the new macro. This was done to generate all the other two input macros.
Inputs
&in &in1 &in2
These integer parameter are the input parameters to the parse_v_on... macros. The parse_v_on_true and parse_v_on_false macros use the single input in, whilst the two inputs macros use the inputs in1 and in2. These inputs are evaluated by the macros to determine whether the parse_v module should be triggered.
v_commands active on_inst relative
These parameters are all used by the standard parse_v module. The v_commands parameter is a string value that allows the v code that should be processed to be stored. The other parameters control the way the parse_v module works. For full details please see the parse_v documentation.
Outputs
(none)
Truth Table
This table is intended to describe exactly how these macros will behave in logical terms. It uses the same logic operators as the v language uses.
| Macro Name |
parse_v module triggered |
| parse_v_on_true |
in != 0 |
| parse_v_on_false |
in == 0 |
| parse_v_on_equal |
in1 == in2 |
| parse_v_on_not_equal |
in1 != in2 |
| parse_v_on_less_than |
in1 < in2 |
| parse_v_on_greater_than |
in1 > in2 |
Files
xp_comm_proj/common/lg_wdgts.v contains the V definitions of the If..., Toggle, Switch and parse_v_on... macros.
Other Notes
The LogicWidgets library inherits its process. As this library contains no procedural code, the process is not important. The CommonMods library contains all procedural code used by the Common project and should be compiled.
Authors
Andrew Dodd, Various


#
First Name
Last Name
Username
1
Mark
Otto
@mdo
2
Jacob
Thornton
@fat
3
Larry
the Bird
@twitter
Panel title
Panel content
Panel title
Panel content
Panel title
Panel content
Panel title
Panel content
Panel title
Panel content


Bug summary:
App will crash if user tries to add a new time range for a task entry
Observed Behavior (a description of what happened with the app):
The app will crash when a user tries to add a new time range to an existing task entry.
Expected Behavior (a description of what you expected to happen):
The user should be able to perform "add a new time range action" on an existing task entry.
Steps to Reproduce (the steps to reproduce the problem):
1. User clicks the three-dot button to see action list
2. User chooses the "Add task" option
3. User inputs task name and click "Add task" button to create a new entry
4. User long-press the entry to see the option list
5. User chooses the "Show time" option
6. User clicks the three-dot button to see the action list
7. User chooses the "Add a new time range" action
8. App crashes and exits
Additional information:
Attachments:


[ all classes ]
[ emily.command.meta ]
Coverage Summary for Class: Reactions (emily.command.meta)
| Class | Class, % | Method, % | Line, % |
|---|---|---|---|
| Reactions | 0% (0/ 1) | 0% (0/ 5) | 0% (0/ 10) |
1 package emily.command.meta;
2
3 import emily.util.Emojibet;
4
5 public enum Reactions {
6 STAR(ReactionType.USER_INPUT, Emojibet.STAR, "Starboard, See the starboard command for more info"),
7 SKIP_TRACK(ReactionType.MUSIC, Emojibet.NEXT_TRACK, "Vote to skip the now playing track"),
8 ;
9
10 private final ReactionType reactionType;
11 private final String emote;
12 private final String description;
13
14 Reactions(ReactionType reactionType, String emote, String description) {
15
16 this.reactionType = reactionType;
17 this.emote = emote;
18 this.description = description;
19 }
20
21 public String getDescription() {
22 return description;
23 }
24
25 public String getEmote() {
26 return emote;
27 }
28
29 public ReactionType getReactionType() {
30 return reactionType;
31 }
32 }


I create web applications as toolkits that fit companies needs to automate processes, increase productivity and perform business functions accurately.
Find Out MoreI am a full stack web developer, focused on developing applications that can digitize processes in companies, make them faster and more rigorous, contributing to the development and success of companies!
I am formed by NumericALL in Belval, Luxembourg in the most current programming languages:
Get Started!
My work results from listening to the client.
I'm in continuous learning, to be able to offer innovation and vision.
I am open minded, I have experience working in multicultural environments and I speak several languages!
Words for what? 'Letz' code!
Ready to start your next project with me? Give me a call or send me an email and I will get back to you as soon as possible!


Iron Man, American comic book superhero, a mainstay of Marvel Comics, who first appeared in 1963 in Tales of Suspense no. 39. His creation is officially credited to four people: writer and editor Stan Lee, who plotted the first story; his brother Larry Lieber, who scripted it; artist Don Heck, who drew it; and Jack Kirby, who designed Iron Man’s original armoured battlesuit.
Iron Man possesses a wealth of powers through his powered armor suit. These powers include super strength, the ability to fly, durability, and a number of weapons. The primary weapons used by Iron Man are rays that are shot from the palms of his gauntlets.


Eiffel-community Vulnerability and Security Reports
Publicly Disclosed Security Vulnerabilities and Fixes


The message(s) to forward, or their integer IDs.
If the given messages are integer IDs and not instances of the Message class, this must be specified in order for the forward to work.
Whether the message should notify people with sound or not.
Defaults to false (send with a notification sound unless the person has the chat muted). Set it to true to alter this behaviour.
If set, the message(s) won't forward immediately, and instead they will be scheduled to be automatically sent at a later time.
Generated using TypeDoc
interface used for forwarding messages


The action of a rule is evaluated when the corresponding pattern is matched. The result of its evaluation is the result that the lexical analyser returns to its caller.
We can think of an action like this: it is a form which is placed in the
body of a lambda
function, which in turn is invoked when a token
matching the regular expression is found. So the following
specification:
decint [0-9]+ %% {decint} (string->number yytext)
will cause the following code to be put in the generated lexer tables:
(lambda (yytext) (string->number yytext))
arguments in the formals of the lambda
are local bindings we can
use in our actions. There are a few local bindings that are accessible
by the action when it is evaluated: yycontinue
, yygetc
,
yyungetc
, yytext
, yyline
, yycolumn
and
yyoffset
.
Contains the lexical analysis function itself. Use
(yycontinue)
to ask for the next token.
Contain functions to get and unget characters from the input of the analyser. They take no argument.
yygetc
returns a character, or the ‘(eof-object)’ value if the end–of–input is reached.They should be used to read characters instead of accessing directly the input port because the analyser may have read more characters in order to have a look–ahead.
If we get more characters than we unget: those characters are skipped by the lexer function at the next invocation. If we want to perform a lookahead without loosing characters, we must unget all the characters we have got.
It is incorrect to try to unget more characters than has been gotten since the parsing of the last token. If such an attempt is made,
yyungetc
silently refuses.
Bound to a string containing the lexeme. This string is guaranteed not to be mutated. The string is created only if the action seems to need it. The action is considered to need the lexeme when ‘yytext’ appears somewhere in the text of the action.
Indicate the position in the input at the beginning of the lexeme.
yyline
is the number of the line; the first line is numbered 1.yycolumn
is the number of the column; the first column numbered 1.It is important to mention that characters such as the tabulation generate a variable length output when they are printed. So it would be more accurate to say that
yycolumn
is the index of the first character of the lexeme, starting at the beginning of the line.
yyoffset
indicates the distance from the beginning of the input; the first lexeme has offset 0.The three bindings may not all be existent depending on options given to the function
lex
when generating the tables.
There is a default action that is provided for a rule when its action is omitted.
It is clearer (and normally more useful) to specify explicitly the action associated with each rule.


Installation
This post will discuss the installation steps you need to go through to set this blog up.
Prerequisites
In order for this blog to be hosted on
This repository consists of 2 branches, namely master
and jekyll
. The latter
is the branch that holds the actual jekyll project. Because we use some plugins
that are not allowed on github we will have to build locally. The master
branch only contains static HTML files.
So proceed by creating the repository in your own github account. I will assume
that your username is username
and the title of the github repository is thus
username.github.io
. You can then proceed executing following commands:
git clone git@github.com:cdetroye/cdetroye.github.io.git
mv cdetroye.github.io username.github.io
cd username.github.io
git remote set-url origin<EMAIL_ADDRESS>git push remote --all
At this point you will have an exact copy of this repository on your own
github. Recall that I said that GitHub expects you to have only static files on
the master branch because we use “exotic” plugins. This means that we have to
somehow get the output from jekyll build
(which is located in _site
) to the
master branch. To make this process easy I have provided a pre-commit
hook
file located in bin/update-script
. So in order to make the process painless
you will have to create a symlink to that script file. To do so, execute:
ln -s bin/update-site .git/hooks/pre-commit
This will execute the following code each time before you commit:
#!/bin/bash
set -e
# Build the jekyll site
jekyll build
# Make a copy of the master branch
git clone -b master . .temp/
cd .temp/
# Copy the files
/bin/cp -rf ../_site/* .
 It just makes sure that your html files are in the
top-level of your master branch. This means that you can only make changes to
the jekyll
branch and should not touch the master
branch.


MIDI Class Device Mode Configuration and State Structure. More...
#include <MIDI.h>
Data Fields | |
| struct { | |
| uint8_t StreamingInterfaceNumber | |
| uint8_t DataINEndpointNumber | |
| uint16_t DataINEndpointSize | |
| bool DataINEndpointDoubleBank | |
| uint8_t DataOUTEndpointNumber | |
| uint16_t DataOUTEndpointSize | |
| bool DataOUTEndpointDoubleBank | |
| } | Config |
| struct { | |
| } | State |
Class state structure. An instance of this structure should be made for each MIDI interface within the user application, and passed to each of the MIDI class driver functions as the MIDIInterfaceInfo parameter. This stores each MIDI interface's configuration and state information.
| struct { ... } USB_ClassInfo_MIDI_Device_t::Config |
Config data for the USB class interface within the device. All elements in this section must be set or the interface will fail to enumerate and operate correctly.
Indicates if the MIDI interface's IN data endpoint should use double banking.
Endpoint number of the incoming MIDI data, if available (zero if unused).
Size in bytes of the incoming MIDI data endpoint, if available (zero if unused).
Indicates if the MIDI interface's IN data endpoint should use double banking.
Endpoint number of the outgoing MIDI data, if available (zero if unused).
Size in bytes of the outgoing MIDI data endpoint, if available (zero if unused).
| struct { ... } USB_ClassInfo_MIDI_Device_t::State |
State data for the USB class interface within the device. All elements in this section are reset to their defaults when the interface is enumerated.
Index of the Audio Streaming interface within the device this structure controls.


The Swift Reduction
Package Users' Manual
by Stefano Covino, 21 Feb 2017, v. 4.2.0
Background
The Swift Reduction Package (hereafter SRP) is a packet of command line tools to solve
problems (e.g. basic reduction and analysis tasks of optical/NIR astronomical
data, quick cosmological computations, units conversions, etc.) often met in
astronomical research activities.
SRP was originally
developed in the context of the Swift follow-up activities of the Milan GRB team at the INAF/Brera Astronomical Observatory. The package is designed to be an aid to any
researcher to drive further observation of a followed-up GRB counterpart and
“swift” can therefore be read simply as “rapid”, “agile”, etc.
The package is continuously upgraded and improved.
Within the limits of our basic project choice (i.e. to provide an as simple as
possible tools rather than a very powerful but complex
reduction/analysis/computation environment) any help is absolutely welcome.
Some technical comment
This package, written in Python (v. 3.x), has been widely tested only on PC-Linux and on Mac OS X
workstations. You are anyway absolutely free to use, modify, redistribute this
package as you like.
Of course, in any case, we decline any
responsibility for the use of this package. Given that the sources are
available, and the algorithm public, the results are entirely under your own
responsibility.
Mailing-List
Due to the nature of the SRP project it
quite likely to have frequent update and improvements of the various routines
as well as a continuous bug fixing (and new bugs are definitely introduced
after any feature additions...). Therefore, if you want to be warned each time
a new version is delivered, please send an e-mail to the following address<EMAIL_ADDRESS>with subject simply SRP.
Installation
If you are just updating SRP the simplest
solution is to download the package from the PyPI archive with:
sudo easy_install -U -N SRPAstro
or, for pip supporters:
sudo pip install -U --no-deps SRPAstro
If you, instead, are installing SRP for the
first time or maybe you are upgrading to a new Python release, it is
likely you need to install the many different libraries SRP relies on.
In principle the command:
sudo easy_install SRPAstro
or
sudo pip
SRPAstro
should again do the job. You might also consider to
install the package in a virtual python environment if you do not want to interfere with the system
python installation.
However, some of the required libraries can (will) ask
for more concerned actions for their installation. Indeed, in essentially all
cases, browsing the web you can quickly find the solution to any problem. However,
an alternative and strongly advised procedure is to install one of the available open-source
self-contained scientific python installations as the Anaconda distribution (first choice). Most of the
required libraries would then available with no further efforts and SRP is installed smoothly.
In addition to the “core” SRP package there
are additions to cover specific tasks or applications:
a.
SRP.FITS, providing general tools to handle FITS files usually, but not
necessarily, obtained by optical/NIR telescopes.
b.
SRP.REM, providing a few commands to work with REM telescope data.
c.
SRP.TNG, providing a few commands to work with TNG telescope instruments.
d.
SRP.NOT, providing a few commands to work with NOT telescope instruments.
e.
SRP.GW, providing tools to manage big catalogues to look
for gravitational wave electromagnetic counterparts.
f.
SRP.SRPPipelines, general tools to develop pipelines for massive data reduction
g.
SRP.SRPPipelines.REM, REM telescope pipeline command.
h.
SRP.SRPPipelines.TNG, TNG telescope pipeline commands.
Only the “core” SRP, the SRP.FITS, SRP.REM and SRP.TNG sub.packages are distributed for general use.
Step by step “how to”
This are just examples of what you can do with SRP.
Please, pay attention that the main emphasis in developing these tools is put
in the rapidity and friendly use rather than in getting the very best solution
for any possible case. However, experience says that in most cases the results
are fully acceptable.
Spectroscopy data analysis
1.
Air /
Vacuum wavelength conversion
_
This is
a simple tool to convert air wavelength to/from vacuum wavelength. SRPAirVacuum
-A 6562.801.
2.
DLA ,
IGM, and line profiles
_
We can
also derive the absorption factor due to Dumped Lyman_ systems with SRPDLA
-l 0.4 -n 1e21 -z 1.0 and due to IGM with SRPIGM -l 1.1 -x 0.9 -t 7.8.
For a general transition and a more accurate modeling you can derive the
absorption factor with SRPLineProfile -n 1e20 -b 1 -l 1300 -t TiII_3073.
This function compute a Voigt profile taking into account both Döppler and
intrinsic broadening.
3.
Solar
abundances
_
Element
abundances in the Sun can be retrieved i.e. with SRPSolarAbundance -e Ne.
Data are from Asplund et al. (2009, ARA&A, 47, 481).
Magnitude, flux, frequency, absorption and
reddening
1.
Magnitude
to/from flux conversion
_
It is
quite common to have to convert magnitudes to physical units. To do that it is
enough to run SRPMagFlux -b R -m 18.0 0.03. You will get the effective
frequency, flux and 1-_ error for magnitude, 1-_ error and band reported. The
output unit is Jansky or erg s-1cm-2A-1. It is of course possible to derive
magnitudes from fluxes with the same command: SRPMagFlux -b R -j 1e-5 2e-7.
2.
Reddening
determination and absorption factors
_
Assuming
to know the color excess EB-V it is possible to estimate the amount
of reddening at a given wavelength with SRPDustAbs -g MW -w 0.7. The
wavelength unit is micron and the output is expressed in magnitudes. Extinction
curves for the MW, the LMC and the SMC (Pei, 1992, ApJ, 395, 130) and a generic
starburst galaxy (Calzetti et al., 2000, ApJ, 533, 682). It is also possible to
know the absorption factor due to neutral gas in the X-rays (Morrison &
McCammon, 1983,
ApJ, 270, 119) with SRPNhAbs -e 1 -n 1e21.
3.
Flux
density and energy-frequency conversion
_
SRPPLFluxDensity allows you to compute the flux density at any given energy assuming
to have a power-law spectrum and the integrated flux, i.e. SRPPLFluxDensity -f
2.4e13 -s 1.7. The integrated flux is supposed to be expresses in
erg/s*cm2, the energy in keV, and the flux density is expressed in Jy. With SRPEnergyFreqFlux
-e 1 -j 1e-6 you can convert energy to frequency or wavelength and
vice-versa and flux densities from Jy to erg/s cm2 Ā and viceversa.
Energy is expressed in eV, frequency in Hz and wavelength in micron.
4.
Atmospheric
absorption
-
Atmospheric
extinction coefficients for a few observing sites can be derived with SRPAtmExtinction
-w 0.55 -s LaSilla.
Tables and catalogues
1.
Catalogue
query
_
Given a
position in the sky and a radius with the command SRPQuery -a 01 23 45 -d 23
32 00 -c BS -r 120 you find objects in a catalogue among those
available. The radius unit is arcmin. With SRPNameResolver
-n "Sirius" you can obtain, from SIMBAD, the
coordinates of a known astrophysical source.
2.
Table
extraction
_
This
command helps you to extract only selected columns from a table for further
analyses. It is also possible to skip header rows as in SRPTabExtract -t
table.txt -c '2 3 4 5' -o _output.txt -j 2.
3.
Object
extraction
_
You can
select a single, or more, objects in a table basing on their coordinates with SRPGetTabEntry
-i table.dat -c 2 3 -C 240.45 312.23 -t 1. It is possible to work with
angular or Cartesian coordinates. You can also filter selected objects from a
table with the same command.
4.
Table
match
_
This command
allows you to find the common objects between two tables (i.e. the SRPPhotometry
output). You must provide the file names of the table, shifts in both axes,
and the maximum tolerance (first match and fine tuning) for object matching: SRPMatch
-r refile.dat -m matchfile.dat -t 5 2.5 -o _outfile.dat. Same table scale
and orientation is assumed. If, on the contrary, you want to find common
objects with the same angular coordinates in two tables, you can try SRPMatchCoord
-r refile.dat -m matchfile.dat -t 1 -o _outfile.dat.
Observation management
1.
Target
visibility
_
Providing
geographic position of the observer, target coordinate and a time reference you
can know the azimuth and altitude of the target and the Moon and Sun
separation. It is thought as a simple aid for observation planning: SRPVisibility
-o 10:11:12 -20:21:22. In case you do not provide any input apart from
target coordinate the ESO-La Silla site and the present date are assumed.
2.
Date
conversion
_
It
could be useful to quickly convert from/to dates in "regular" format
(yyyy/mm/dd hh:mm:ss.dd) to Julian Date of Modified Julian Date. This can be
done with SRPCalendar -v -d 2009/4/8 10:51:00.
3.
Finding-chart
creation
_
In
order to quickly generate nice-looking (hopefully) finding charts you can use SRPFindingChart
-f fitsfilename.
Statistics
1.
Gaussian
distribution
_
Providing
mean and standard deviation you can generate an arbitrary number of values
following a given Gaussian distribution: SRPGaussDistrib -m 3 -s 0.1 -n 10.
2.
Gaussian
probability
_
You can
compute Gaussian 1-tail or 2-tail probability distribution given a value in
units of sigma: SRPGaussProb -s 3 -2.
3.
Chi
square surface
_
You can
easily derive the increment for the chi square function given some degrees of
freedom at a given probability with SRPChiSqIncrement -p 90 -d 5. Else,
you can compute the probability to have a chisquare higher than the obtained
value by chance with SRPChiSqIncrement -c 10 -d 7.
4.
Sigma-clipped
average
_
It is
often useful to can evaluate a sigma-clipped average for input data from a
file. You can do that with SRPAverSigmaClipping -i inputtab.txt -d 4 -k 5.
5.
Histogram
creation
_
This
command takes a column from a file as input and computes an histogram. The
output is a table with bin center, bin size, and number of objects in the bin.
Histogram parameters as minimum (i.e. 1), maximum (i.e. 10) and bin size (i.e.
0.2) can be chosen as in SRPHistogram -c 2 -t table.txt -o _output.txt -b 1
10 0.2.
6.
F-Test
computation
_
You can
check the improvement of a fit quality adding parameters with the F-test: SRPFTest
-n 14.45 12 -o 16.34 14.
Afterglow data and cosmology
1.
Afterglow
flux and frequencies
_
SRPAftTypSynchrFluxConst(Wind) allows you to compute the cooling (typical)(self absorption)
synchrotron frequency (Hz) in case of constant ISM (wind). You compute the flux
(Jy) at the typical synchrotron frequency and the flux for a typical afterglow
spectrum at any frequency. From Zhang & Meszaros, IJMPA
A19, 2385 (2004) and Hurley, Sari and Djorgovski, in "Compact Stellar
X-ray Sources" (Cambridge University Press).
2.
Cosmological
parameter computation
_
This
command allows one to compute the Hubble, angular diameter, comoving and
luminosity distances from a minimum to a maximum redshift in any expanding
universe. The distance modulus is also derived. Universe parameters, i.e.
matter density, cosmological constant, etc. can be provided. SRPCosmology -v
-z 1.5 you get the various distances for the default
"concordance" cosmological model.
Miscellanea
1.
SRP running version
-
You can
know the present SRP version with SRPVersion.
2.
Polarization
data
-
Polarization
data can be converted to/from Stokes parameters with SRPStokesPol -s 0.1
0.01 -0.1 0.01 0.0 0.0.
List of commands
3.
SRPAftSynchrSpectrumConst
_
Its
purpose is to compute the afterglow synchrotron spectrum in case of constant
density ISM.
4.
SRPAftSynchrSpectrumWind
_
Its
purpose is to compute the afterglow synchrotron spectrum in case of wind.
5.
SRPAirVacuum
_
Its
purpose is to convert air wavelength to vacuum wavelength and viceversa.
6.
SRPAtmExtinction
_
Its
purpose is to derive atmospheric extinction coefficients.
7.
SRPAverSigmaClipping
_
Its
purpose it to compute a sigma-clipped average for input data.
8.
SRPCalendar
_
Its
purpose is to convert dates from/tom various formats.
9.
SRPChiSqIncrement
_
Its
purpose is to compute increment for chi squares.
The
routine allows one to compute the increment for the chi square having a
probability 100-prob% to occur randomly. Typical usage is for deriving
uncertainties for multiparametric fits. Typical usage is
for deriving uncertainties for multiparametric fits.
Alternatively, one can compute the probability to have randomly a higher
chisquare than the one obtained in a fit.
10.
SRPCosmology
_
Its
purpose is to derive cosmological data.
11.
SRPDLA
_
Its
purpose is to derive the absorption factor due to DLA systems.
_
DLA
modeling performed according to Totani et al. (2006, PASP
58,
485)
12.
SRPDustAbs
_
Its purpose is
to compute the amount of reddening at a given wavelength.
Extinction curves for the MW, LMC and SMC galaxies following Pei
(1992,
ApJ, 395, 130) and starburst galaxies following Calzetti et
al.
(2000, ApJ, 533, 682)
13.
SRPEnergyFreqFlux
_
Its
purpose is to convert energy to frequency or wavelength and vice-versa.
14.
SRPGaussDistrib
_
Its purpose is to generate number
following the Gaussian distribution.
15.
SRPGaussProb
_
Its purpose is to compute probability for
Gaussian distributions.
16.
SRPGetTabEntry
_
Its purpose is to find selected objects in
a table.
17.
SRPHistogram
_
Its purpose is to compute an histogram of
input data.
18.
SRPIGM
_
Its purpose is to derive the absorption
factor due to IGM systems.
19.
SRPLineProfile
_
Its purpose is to compute line profile for
a specific transition.
_
Line profile computed by Voigt function computation.
20.
SRPMagFlux
_
Its purpose is to convert magnitudes
to/from fluxes.
21.
SRPMatch
_
Its purpose is to find common objects
between two tables.
22.
SRPMatchCoord
_
Its purpose is to find common objects,
with the same angular coordinates, in two tables.
_
23.
SRPNameResolver
_
Its purpose is to find the coordinates of
a known astrophysical source from SIMBAD.
24.
SRPNhAbs
_
Its purpose is to compute the amount of
absorption at a given energy.
_
Based on photoelectric absorption cross sections in
Morrison &
McCammon
(1983, ApJ, 270, 119)
25.
SRPPLFluxDensity
_
Its purpose is to derive flux density
known a power-law spectrum and integrated flux.
26.
SRPQuery
_
Its purpose is to extract a region from a
catalogue.
_
For several catalogues you need a working internet
connection.Other catalogues are local.
27.
SRPSelect
_
Its purpose is to allow to create list of
frames satisfying some criterion.
28.
SRPSessionName
_
Its purpose is to define a new session
name.
29.
SRPSolarAbundance
_
Its purpose is to derive the Solar
abundance of various chemical elements.
Data
are from Asplund et al. (2009, ARA&A, 47, 481)
30.
SRPStokesPol
_
Its purpose is to convert from
polarization to Stokes parameter and viceversa.
31.
SRPTabExtract
_
Its purpose is to extract selected columns
from a table.
32.
SRPVersion
-
its purpose is to show the running SRP
version.
33.
SRPVisibility
_
Its purpose is to compute the visibility
of a sky object.
Bugs,
comments, etc.
Of course, as
already stated, any contribution from anyone is welcome. In case you find bugs,
have improvements to suggest, would like to contribute to the code, etc. Please
send an e-mail to Stefano Covino<EMAIL_ADDRESS>We can not
promise to take into account all your comments, but we will anyway try to
improve the package to meet your needs.
Credits,
thanks, etc.
A lot of
people gave some contribution to the SRP and among them I want to quote
Nino Cucchiara, Paolo D'Avanzo, Luca Di Fabrizio, Dino Fugazza, Auvet
Harutyunyan, Nauzet Hernandez, Domenico Impiombato, Gianluca Israel, Daniele
Malesani, Emilio Molinari and Ruben Salvaterra. I also thank ESO and TNG since part of
this code was developed during visitorships in Garching and La Palma.


Dev's week 7 Cultural Blog Site
Cultural Blog: Spirituality
Spirituality
- I try to live up to these values: 5
- The last topic someone asked me for advice on was starting a family. I gave my honest thoughts, shared my experiences, and offered to answer any questions for them in the future.
- I think that sprirituality can help when you are frustrated or stressed. Taking deep breaths and relaxing can sometimes bring answers to problems.


Episode List for Podcast:
TBD
Unique Id
Podcast Id
Episode Id
Episode Name
Processing Status
Origin URL
File Size
S3 URL
Actions
Unique ID
podcastId
episodeId
episodeName
processingStatus
Origin URL
fileSize
s3URL
Transcribe
View Transcription