Reading — step 1 of 5
Learn
~2 min readControl Flow and Subroutines
Strings are first-class in Perl. The language was designed for them.
Concatenation with .:
my $s = "hello" . " " . "world"; # "hello world"
$s .= "!"; # append in-place
Repetition with x:
my $line = "-" x 30; # 30 dashes
my @row = (0) x 5; # (0, 0, 0, 0, 0)
Length with length:
length "hello" # 5
Case:
uc "hi" # "HI"
lc "HI" # "hi"
ucfirst "hello" # "Hello"
lcfirst "HELLO" # "hELLO"
Substring — substr is read OR write:
my $s = "hello world";
print substr($s, 0, 5); # "hello"
print substr($s, 6); # "world" (to end)
print substr($s, -5); # "world" (negative offset)
substr($s, 0, 5) = "howdy"; # in-place replace
Index search:
index("hello world", "world") # 6
index("hello world", "xyz") # -1 (not found)
rindex("hello hello", "hello") # 6 (last occurrence)
sprintf — formatted string (like printf to a string):
my $msg = sprintf("%s scored %d (%.1f%%)", "Ada", 95, 95.0);
# "Ada scored 95 (95.0%)"
Format specifiers: %d integer, %f float, %s string, %x hex, %-10s left-pad, %5d right-pad, %.2f 2 decimals.
split and join:
my @parts = split /,/, "a,b,c,d"; # ("a", "b", "c", "d")
my $back = join ",", @parts; # "a,b,c,d"
split /\s+/, $line; # split on whitespace
split //, "hello"; # ('h','e','l','l','o') — empty pattern
tr/// — transliteration (NOT regex). Translate or count characters:
my $s = "hello";
(my $upper = $s) =~ tr/a-z/A-Z/; # "HELLO"
my $vowels = ($s =~ tr/aeiou//); # 2 (count vowels)
reverse — works on strings AND lists:
reverse "hello"; # in scalar context: "olleh"
reverse(1, 2, 3); # (3, 2, 1)
chomp vs chop:
chomp $s— remove trailing\n(or whatever$/is)chop $s— remove last character regardless
Comparison: eq, lt, cmp (NEVER == or < for strings):
"apple" eq "apple" # true
"apple" lt "banana" # true (alphabetical)
"apple" cmp "banana" # -1
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…