Perl - Miscellaneous

perl

How can we define a sub-routine?

sub good_word {
    my ($some_name, $some_guess) = @_; # @_ is an array that hold all parameters
}
sub subName { ... }        // No prototype
sub subName() { ... }        // prototype void
sub subName($$) { ... }    // prototype to 2 scalars
sub subName(\%) { ... }    // prototype to one hash ref

How can we access the parameters that were passed to a sub-routine?

Inside the sub-routine, we have:

  1. @_ is an array that hold all parameters
  2. $_[0] represent the first parameters
  3. $_[1] represent the second parameters, etc

What is the syntax for the foreach loop?

foreach $name (sort keys(%hash)) {
    ...
}

How can we express a number using exponent form?

2 ** 3;  # 2^3

What is the string concatenation operator?

.

The string concatenation operator is a dot.

What is the repeat operator?

x
"fred" x 3; # "fredfredfred"

How can we append a space to a string?

$str .= " ";

How can we invoke a subroutine via its reference?

$coderef->(1,2,3);    // invoke a subroutine
&{$coderef}(1,2,3);    // same as above

What is a hard reference and what is a symbolic reference?

$x = \$y;        // $x is a hard reference to $y.
            // $x point to the location of $y.

$$x        // symbolic reference (same as hard reference), the value
        // of $x is evaluated and used as the name of the variable,
        // rather than direct link to anonymous value.
$y = 5;
$x = 'y';
print $$x;    // This is a symbolic reference.  This print out 5.

How can we use the grep function?

@res = grep BLOCK LIST;
@res = grep EXPR LIST;
@res = grep {!/^#/} @bar;     // weed out comment

grep evaluates BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consisting of those elements for which the expression evaluate to TRUE. In scalar context, return the number of times the expression was TRUE.

How can we use the map function?

may BLOCK LIST;
map EXPR LIST;
@chars = map { split// } @strs;    // returns all characters found

Evaluate BLOCK or EXPR for each element of LIST (locally setting $_ to each element of LIST) and return a list whose value composed of results of each evaluation. Evaluates BLOCK or EXPR in a list context, so each elements of LIST may produce zero, one, or more elements in the returned value. In scalar context, returns the total number of elements so generated.

%hash = map { chr($_) => $_ } @array;

In the above example, each evaluation return 2 elements (a character and a number), so the resulting hash has characters as keys and numbers as values.

How can we override built-in function?

Built-in functions may only be done by importing from a module. Ordinary predeclaration isn't good enough. However, the 'subs' pragma (compiler directive) let you, in effect, predeclare subs via the import syntax, and these names may then be override the built-in ones.

use subs 'chdir', 'chroot', 'chmod','chown';
chdir $somewhere
sub chdir { ... }

To refer to builtin function, precede the builtin name with the qualifier CORE::

How can we convert perl script into an executable binary?

perlcc -prog filename -o executableName

How can we turn a process into a background process that is completely detached from the terminal?

use POSIX 'setsid';
sub daemonize {
    chdir '/' or die "Cannot chdir to /: $!";
    open STDIN, "/dev/null' or die "Cannot read /dev/null: $!"
    open STDOUT, ">/dev/null" or die "Cannot write to /dev/null: $!";
    defined(my $pid = fork) or die "Cannot fork: $!";
    exit if $pid;
    setsid or die "Cannot start a new session: $!";
    open STDERR, '>&STDOUT' or die "Cannot duplicate STDERR to STDOUT";
}

The fork() has to come before the setsid() call. So, in order to turn a process into a background process that is completely detached from the terminal, we just have to write the daemonize method as above, and then invoke it.

What is the definition of the term 'lexical variables'?

Lexical variables are those declared with "my". They do not live in a symbol table and thus they are not available from outside the block in which they were declared. Lexical variables can only refer to scalar, array, or hash. They cannot refer to file handles, directory handle, formats and other typeglobs.

What are the limitations with 'lexical variables'?

Lexical variables are those declared with "my". They do not live in a symbol table and thus they are not available from outside the block in which they were declared. Lexical variables can only refer to scalar, array, or hash. They cannot refer to file handles, directory handle, formats and other typeglobs.

What is the purpose of the @INC array?

The @INC array is a special Perl variable equivalent to the shell's PATH variable. The shell's PATH variable contains a list of directories to search for executable. The Perl's @INC array contains a list of directories from which Perl search for modules and libraries.

What is the purpose of the %INC hash?

The %INC hash is another Perl special variable that is used to cache the names of the files and the modules that were successfully loaded.

What is the difference between a use statement that include parenthesizes and a use statement that does not include parenthesizes?

use MyModule;
use MyModule();

The above 2 statements differ in the following way: The first statement does call MyModule->import which will import the defaults. The second statement does not call MyModule->import, thus those that are mark to be exported by default via the @EXPORT array do not get imported.

Other commands:

chr($a)    // return the corresponding character (in this case $a is number)
ord($a)    // return the corresponding ordinal number (in this case $a is a character)
lc $str    // return the string lower-cased
lcfirst $str    // return the string with the first letter lower-cased
uc, ucfirst    // return the string upper-cased
length $str    // return the length of the string

index STR, SUBSTR, POSITION    // returns the position of the first occurrence of SUBSTR
index STR, SUBSTR            // in STR starting at the beginning or from POSITION
                        // if specified.  Return -1 if SUBSTR is not found

rindex STR, SUBSTR, POSITION    // Similar to index, but return the position of
rindex STR, SUBSTR            // the last occurrence of SUBSTR in STR

substr EXPR, OFFSET, LEN, REPLACEMENT    // returns a substring starting at
substr EXPR, OFFSET, LEN                // OFFSET that is LEN in length
substr EXPR, OFFSET

exist EXPR        // return true if the specified hash key exists, regardless of the corresponding value.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License