Perl - Sigill


What are some special variables and their corresponding English names?

$OS_ERROR => $!

Global symbols, my(), and local():

There is one symbol table for each package (which is why global symbols are really package global symbols).

There is no typeglob associated with a lexical variable and a lexical variable can refer only to a scalar, an array, a hash, or a code reference. Since perl 5.6, it can also refer to a file glob.

With 'use vars()', you are making an entry in the symbol table, and you are telling the compiler that you are going to be referencing that entry without an explicit package name.

With my(), NO ENTRY IS PUT IN THE SYMBOL TABLE. The compiler figures out at compile time which my() variables are the same as each other, and once you hit runtime you cannot go looking those variables up in the symbol table.

local() creates a temporal-limited package-based scalar, array, hash, or glob — when the scope of the definition is exited at runtime, the previous value (if any) is restored. References to such variable are also global…only the value changes (This is what cause variable suicide).

my() create a lexically-limited non-package-based scalar, array, or hash — when the scope of definition is exited at compile-time, the variable ceases to be accessible. Any references to such a variable at runtime turn into unique anonymous variables on each scope exit.

How can we create an anonymous hash reference?

Use { } to create anonymous hash references.

How can we create an anonymous array reference?

Use [ ] to create anonymous array references.

How can we define a scalar variable?

my $x = 5;

Scalar variable names start with a dollar sign.

How can we define an array?

my @students = ( { name         => 'Clara',
                   registration => 10405,
                   grades       => [ 2, 3, 2 ] },
                 { name         => 'Amy',
                   registration => 47200,
                   grades       => [ 1, 3, 1 ] },
                 { name         => 'Deborah',
                   registration => 12022,
                   grades       => [ 4, 4, 4 ] } );

An array variable names start with the at symbol (@).

How can we iterate over an array?

# print out names of all students
foreach my $student (@students) {
    print $student->{name} . "\n";

In the above code, @students is an array of anonymous hash. As we iterate over each element of the @students array, the value of each element of the @students array is assigned to the $student variable. Therefore, $student is a hash. To access the name of the student, we use the the -> operator.

# print out Clara's second grade
print $students[0]->{grades}->[1];

# delete Clara's registration code
delete $students[0]->{registration};
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License