← Perl EnglishChapter 02 of 13

Variables

## Learning Objectives - Understand Perl variable types - Work with scalar variables - Use arrays and lists - Use hash (associative arrays) - Understand references - Work with typeglobs ## Variable Types | Type | Prefix | Example | |------|--------|---------| | Scalar | `$` | `$name`, `$age` | | Array | `@` | `@names`, `@numbers` | | Hash | `%` | `%data`, `%config` | | Typeglob | `*` | `*file` | | Reference | `\` | `\$scalar`, `\@array` | ## Scalar Variables ### Declaration and Assignment ```perl use strict; use warnings; my $name; # Declaration $name = "Alice"; # Assignment my $age = 30; # Declaration + Initialization my $price = 19.99; # Floating point my $count = undef; # Undefined value ``` ### String Scalars ```perl my $name = "Alice"; my $greeting = 'Hello'; # Single quotes - no interpolation my $message = "Hello, $name!"; # Double quotes - interpolation my $escaped = "She said \"Hi\""; # Escape characters my $concat = "Hello " . "World"; # Concatenation ``` ### Numeric Scalars ```perl my $integer = 42; my $float = 3.14; my $scientific = 1.5e10; my $hex = 0xFF; # Hexadecimal (255) my $octal = 0777; # Octal my $binary = 0b1010; # Binary (10) ``` ### Undef Values ```perl my $undefined; print defined($undefined) ? $undefined : "undefined"; $undefined = 5; print defined($undefined) ? $undefined : "undefined"; ``` ## Array Variables ### Declaration ```perl use strict; use warnings; my @numbers; # Empty array my @nums = (1, 2, 3, 4, 5); # Array with values my @mixed = ("a", 1, "b", 2); # Mixed types my @range = (1 .. 10); # Range operator (1 to 10) my @letters = ('a' .. 'z'); # Letter range ``` ### Array Operations ```perl my @colors = ("red", "green", "blue"); # Access elements (0-indexed) print $colors[0]; # "red" print $colors[-1]; # "blue" (last element) # Array length print scalar @colors; # 3 print $#colors; # 2 (last index) # Assignment $colors[3] = "yellow"; # Add element $colors[0] = "purple"; # Modify element ``` ### Array Slices ```perl my @nums = (1 .. 10); my @first_three = @nums[0, 1, 2]; # (1, 2, 3) my @slice = @nums[2 .. 5]; # (3, 4, 5, 6) ``` ### Push, Pop, Shift, Unshift ```perl my @stack = (1, 2, 3); push @stack, 4; # (1, 2, 3, 4) my $popped = pop @stack; # Removes 4, returns 4 unshift @stack, 0; # (0, 1, 2, 3) my $shifted = shift @stack; # Removes 0, returns 0 ``` ## Hash Variables ### Hash Declaration ```perl use strict; use warnings; my %empty; # Empty hash my %person = ( name => "Alice", age => 30, city => "Boston" ); # Order is not guaranteed (pre Perl 5.26) ``` ### Accessing Elements ```perl my %person = ( name => "Alice", age => 30, city => "Boston" ); print $person{name}; # "Alice" print $person{age}; # 30 # Modify $person{age} = 31; $person{email} = "alice@example.com"; ``` ### Hash Functions ```perl my %person = (name => "Alice", age => 30); # Keys and values my @keys = keys %person; # ("name", "age") my @values = values %person; # ("Alice", 30) # Each (iteration) while (my ($key, $value) = each %person) { print "$key => $value\n"; } # Check existence if (exists $person{age}) { print "Age exists\n"; } # Delete delete $person{age}; # Size my $size = scalar keys %person; # Number of keys ``` ## References ### Creating References ```perl my $scalar = 42; my @array = (1, 2, 3); my %hash = (a => 1, b => 2); my $scalar_ref = \$scalar; my $array_ref = \@array; my $hash_ref = \%hash; # Anonymous references my $anon_array = [1, 2, 3]; my $anon_hash = { a => 1, b => 2 }; ``` ### Dereferencing ```perl my @colors = ("red", "green", "blue"); my $colors_ref = \@colors; # Dereference to get original my @copy = @$colors_ref; my $first = $colors_ref->[0]; my %data = (x => 10, y => 20); my $data_ref = \%data; my %copy = %$data_ref; my $val = $data_ref->{x}; ``` ### Reference to Functions ```perl sub greet { my ($name) = @_; print "Hello, $name!\n"; } my $greet_ref = \&greet; $greet_ref->("Alice"); ``` ## Complex Data Structures ```perl use strict; use warnings; use Data::Dumper; # Array of hashes my @users = ( { name => "Alice", age => 30 }, { name => "Bob", age => 25 }, ); print $users[0]{name}; # "Alice" # Hash of arrays my %scores = ( Alice => [95, 87, 92], Bob => [88, 91, 85], ); print $scores{Alice}[0]; # 95 # Deep reference my $complex = { users => [ { name => "Alice", scores => [95, 87] }, ], }; print $complex->{users}[0]{scores}[0]; # 95 ``` ## Typeglobs ### Basic Usage ```perl use strict; use warnings; my $scalar = "hello"; my @array = (1, 2, 3); # Typeglob - access all types with same name print *$scalar; # "hello" print *$array[0]; # 1 # Aliasing *another_name = \$scalar; print $another_name; # "hello" ``` ### Filehandle Typeglob ```perl use strict; use warnings; # STDOUT is a typeglob print STDOUT "Hello\n"; print STDERR "Error\n"; ``` ## Variable Scoping ```perl use strict; use warnings; my $global = "outer"; { my $inner = "inner scope"; print $global; # Accessible print $inner; # Accessible } # print $inner; # Error - out of scope ``` ## Summary - Scalar variables (`$`) hold single values - Array variables (`@`) hold ordered lists - Hash variables (`%`) hold key-value pairs - References (`\`) create pointers to variables - Use `->` to access referenced data - Anonymous arrays use `[ ]`, hashes use `{ }` - `my` creates lexical (scoped) variables - Always use `use strict` and `use warnings`

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →