Perl Variables
Perl - Variables in Modern Perl
Section titled “Perl - Variables in Modern Perl”Variables are named storage locations in memory. In Perl, the type of data a variable can hold is indicated by its ‘sigil’ - a special character at the beginning of its name.
Modern Perl programming strongly advocates for use strict; and use warnings;. With use strict;, variables must be declared before use, typically with my, which gives them lexical scope (limited to the enclosing block, file, or eval).
Perl has three main built-in data types, each with a corresponding variable type:
- Scalars (
$): Hold a single value, like a number, a string, or a reference. - Arrays (
@): Hold an ordered list of scalars. - Hashes (
%): Hold an unordered collection of key-value pairs (associative arrays).
Perl maintains separate namespaces for different variable types. This means $name, @name, and %name are distinct variables.
Declaring and Assigning Variables
Section titled “Declaring and Assigning Variables”With use strict; in effect, you must declare variables using my (for lexical scope), our (for package variables, lexically scoped), or state (for persistent lexical variables, Perl 5.10+). The most common is my.
The equals sign (=) is used for assignment.
my $age = 30; # Scalar: integer assignmentmy $name = "Jane Doe"; # Scalar: string assignmentmy $pi = 3.14159; # Scalar: floating-point number
my @colors = ("red", "green", "blue"); # Array of stringsmy %capitals = ( # Hash: key => value pairs "USA" => "Washington D.C.", "France" => "Paris",);Scalar Variables ($)
Section titled “Scalar Variables ($)”A scalar variable holds a single piece of data. This can be a number (integer or floating-point), a string, or a reference (which points to another data structure).
#!/usr/bin/env perluse strict;use warnings;use feature 'say';
my $count = 10;my $message = "Processing complete.";my $temperature = 25.5;
say "Count: $count";say "Message: $message";say "Temperature: $temperature C";Output:
Count: 10Message: Processing complete.Temperature: 25.5 CArray Variables (@)
Section titled “Array Variables (@)”An array variable stores an ordered list of scalar values. Array indices start at 0.
To access a single element of an array, use the $ sigil with the array name, followed by the index in square brackets (e.g., $array_name[0]).
#!/usr/bin/env perluse strict;use warnings;use feature 'say';
my @fruits = ("apple", "banana", "cherry");
say "First fruit: $fruits[0]"; # Accessing the first elementsay "Second fruit: $fruits[1]";
$fruits[2] = "mango"; # Modifying an elementsay "All fruits: @fruits"; # Interpolates the array with spaces
my $num_fruits = @fruits; # In scalar context, an array returns its sizesay "Number of fruits: $num_fruits";Output:
First fruit: appleSecond fruit: bananaAll fruits: apple banana mangoNumber of fruits: 3Common array operations include push (add to end), pop (remove from end), shift (remove from start), and unshift (add to start).
Hash Variables (%)
Section titled “Hash Variables (%)”A hash variable stores a collection of key-value pairs. Keys are unique strings, and values are scalars. Hashes are unordered (though recent Perl versions offer some ordering consistency for iteration, it shouldn’t be relied upon for programmatic logic).
To access a single element of a hash, use the $ sigil with the hash name, followed by the key in curly braces (e.g., $hash_name{key}). The ‘fat comma’ (=>) is often used for readability when defining hashes.
#!/usr/bin/env perluse strict;use warnings;use feature 'say';
my %ages = ( "Alice" => 30, "Bob" => 24, "Carol" => 42,);
say "Alice's age: $ages{Alice}";
$ages{David} = 19; # Adding a new key-value pair
# Iterating through a hashsay "Known ages:";foreach my $name (keys %ages) { # 'keys %ages' returns a list of all keys say " $name is $ages{$name} years old.";}Output (order of iteration may vary):
Alice's age: 30Known ages: Carol is 42 years old. David is 19 years old. Alice is 30 years old. Bob is 24 years old.Variable Context
Section titled “Variable Context”Perl determines how to interpret a variable or expression based on the ‘context’ in which it’s used. The two primary contexts are scalar context and list context.
#!/usr/bin/env perluse strict;use warnings;use feature 'say';
my @elements = ('A', 'B', 'C');
# List context: assigning to an array copies elementsmy @copy_of_elements = @elements;say "Copy: @copy_of_elements"; # Output: Copy: A B C
# Scalar context: assigning to a scalar gives the number of elementsmy $count_of_elements = @elements;say "Count: $count_of_elements"; # Output: Count: 3
# String context (a type of scalar context)my $string_representation = "@elements";say "String: $string_representation"; # Output: String: A B C (elements joined by space)Understanding context is crucial for writing correct Perl code. Other contexts include boolean (true/false evaluation) and void (value discarded).
For further learning, explore references, which allow creating complex data structures like arrays of hashes or hashes of arrays. Also, explore Perl’s object-oriented features for larger applications.