Scalars, arrays and hashes
The three kinds of variable — $scalar, @array, %hash — my, undef, and numbers vs strings.
Runs in Zerethon IDE · Perl 5.40
Official Perl documentation ↗
The sigil says what kind of variable it is: $ one value (a number, a string or a reference), @ a list, % a hash of key/value pairs. Declare each one with my.
main.pl
use v5.40;
my $count = 3;
my $name = "Ada";
my @scores = (70, 95, 82);
my %ages = (ada => 36, alan => 41);
my $nothing;
say "$count $name $scores[1] $ages{alan}";
say "42" + 1, " ", 7 . 7;
say 7 / 2, " ", int(7 / 2), " ", 7 % 2, " ", 2 ** 10;
say defined $nothing ? "defined" : "undef";
say scalar(@scores), " ", $#scores;
say "10" == 10.0 ? "same number" : "different numbers";
say "10" eq "10.0" ? "same string" : "different strings";
Output
3 Ada 95 41 43 77 3.5 3 1 1024 undef 3 2 same number different strings
- One element of
@scoresis a scalar, so it is written$scores[1]; one value of%agesis$ages{alan}. - A value is a number or a string depending on how you use it:
+treats both sides as numbers,.joins them as strings. - Compare numbers with
==,<,<=>; compare strings witheq,lt,cmp. Mixing them up is a common bug. scalar(@array)is the number of elements;$#arrayis the last index.