Perl has three main data types:
Strings can be concatenated by the dot (.) operator:$abc = "abc";
$def = "def";
where strings can be replaced by variables:$str = "abc" . " " . "cde"; # $str has the value 'abc cde'
Concatenation is often useful for readability. However, it is not always necessary. Variable interpolation ( = replacing a variable with the value of that variable) can give correct results:$abc = "abc";
$str = $abc . " " . "cde";# $str has the value 'abc cde'
Shorthand with the$abc = "abc";
$cde = "cde";
$str = "$abc $cde";# $str has the value 'abc cde'
A scalar variable can be defined by other scalar variables:$str = "abc" . " ";
$str .= "cde";# $str has the value 'abc cde'
You could not write here$bird = "penguin";
$no_of_birds = "two";
$bird_type = $bird;# $bird_type has now the value "penguin".
$observation = "I saw $no_of_birds ${bird}s.";# I saw two penguins.
You can assign a value to multiple variables:$bird_type = $bird; # $bird_type has now the value "penguin".
$observation = "I saw " . $no_of_birds . " " . $bird . "s.";# I saw two penguins.
and swap the values easily:($first, $second, $third, $fourth);
$first = $second = "one";
$third = $fourth = "two";
($first, $third) = ($third, $first); # $first has the value 'two' and $third the value 'one'.
$str = "Did you say \"Hello?\"\n"; # backslash necessary
$str = qq(Did you say "Hello?"\n);
$str = 'Did you say "Hello?"' . "\n";# my preferred option
$str = q(Did you say "Hello?") . "\n";
$result = substr("abcdefgh", 2); # the value of $result is cdefgh; strings are zero-based, i.e. the first character has the index 0
$result = substr("abcdefgh", 2, 3); # the value of $result is cde
Find the index of the second occurrence of the substring 'fo': add simply as third argument a start position to start searching.$str = "From forth the fatal loins of these two foes";
$result = index($str, "fo");# the value of $result is 5
If a substring is not found, index returns -1. Use rindex to start searching at the end of a string.$str = "From forth the fatal loins of these two foes";
$result = index($str, "fo", (5 + 2) );# the value of $result is 40
With a start position:$str = "From forth the fatal loins of these two foes";
$result = rindex($str, "fo");# the value of $result is 40
$str = "From forth the fatal loins of these two foes";
$result = rindex($str, "fo", (40 - 1));# the value of $result is 5
So printing scalars to the console/terminal is really easy:print(expression) or print expression (without parentheses; I do not like this option);
$no = "one";
print("$no\n");# prints "one"
$no_1 = "one";
$no_2 = "two";
print("$no_1\n");# prints "one"
To print the last result with a space, use a 'space' element:$no_1 = "1";
$no_2 = "2";
print($no_1, $no_2);# prints 12 (without space!)
To print strings, including variables:$no_1 = "1";
$no_2 = "2";
print($no_1, " ", $no_2);# prints 1 2
$name = "Daniel";
$age = "15";
print("$name is $age years old.");# prints Daniel is 15 years old.
One could have similar results with thefor ($i = 0; $i < length("abcdefgh"); $i++) {
print(substr("abcdefgh", $i, 2));
print("\n");# prints ab cd ef gh on separate lines
}
print(length("abc")); # prints 3
print("abc" x 3); # prints abcabcabc
Easier -at least to remember-:print("2 + 2 = @{[2 + 2]}"); # prints 2 + 2 = 4
print("2 + 2 = " . (2 + 2)); # print("2 + 2 = " . 2 + 2); does not work!
print(scalar(reverse("abc")));
print(lc("ABC")); # prints abc; the uppercase equivalent is: uc
use utf8;
use open qw( :std :encoding(UTF-8) );
print(uc("Čerušňa"));
You could use nested functions.print(ucfirst("abc")); # prints Abc; the lowercase equivalent is: lcfirst
$str = "aBCD";
print(ucfirst (lc($str)));# prints Abcd
print("Rei\unie\ur"); # prints ReiNieR
print("\lRei\lNier");# prints reinier
The string manipulation orchestra can be extended by regular expressions and modules (later more info on that).print("r\Ueinie\Er"); # prints rEINIEr
print("R\LEINIE\ER");# prints ReinieR
You'll get the same result when calling substr with four arguments:$str = "abcdefgh";
substr($str, 3, 3) = "-";
print($str);# prints abc-gh
Replacing the last three characters by *:$str = "abcdefgh";
substr($str, 3, 3, "-");# 3, 3 refers to three characters from the fourth character: 'def'
print($str);# prints abc-gh
$str = "abcdefgh";
substr($str, -3, 3, "*");
print($str);# prints abcde*
$str = "abc";
print(substr($str, 0, 0, "X"));# prints Xabc
$str = "abc";
print(substr($str, 3, 0, "X"));# prints abcX
$str = "abc";
print(substr($str, 2, 0, "X"));# prints abXc
The function 'chop' removes the last character of a string.$str = "abc";
print(substr($str, 0, 1, ""));# prints bc
$str = "abc";
print(substr($str, 0, 2, ""));# prints c
$str = "abc";
print(substr($str, 2, 1, ""));# prints ab
$str = "abc";
print(chop($str));# prints the removed character 'c'
print($str);# prints ab
$str = "abc"; $str++; print("Incremented string: $str\n"); # Output: Incremented string: abd
$str = "a0"; $str++; print("Incremented string: $str\n"); # Output: Incremented string: a1
The character 'z' or 'Z' deserves special attention. When the string 'Z' is incremented, the character 'Z' is incremented to 'A'. However, since this increment operation causes a wraparound (causing 'Z' to reset back to 'A'), a carry-over effect occurs. Since there is no character to the left of the character 'Z' to accommodate the carry-over, Perl adds a new character to the left of the string. So, the result becomes 'AA'.$str = "109"; $str++; print("Incremented string: $str\n"); # Output: Incremented string: 110
$char = "Z"; $char++; print("Incremented character: $char\n"); # Output: Incremented character: AA
In the next example is 'z' preceded by 'a', so a normal carry-over can take place.$str = "z9"; $str++; print("Incremented string: $str\n"); # Output: Incremented string: aa0
Study the following code:$str = "az"; $str++; print("Incremented string: $str\n"); # Output: Incremented string: ba
The string '1a' - starting with a digit and followed by a character from the class [a-zA-Z] - is interpreted as '1' according to Perl's string incrementation rules.$str = "1a"; $str++; print("Incremented string: $str\n"); # Output: Incremented string: 2
1. How to replace multiple horizontal spaces to a single space?
A well-known question with many answers. The cleanest solution is to use the horizontal whitespace character class
outputs:$data = "% a b c %"; $data =~ s/\h+/ /g;
$count has the value 4$str="1bus 2bus 3 bus 4 bus"; $count = $str =~ s/bus/bus/g;
$count has the value 7$str="a;b;c,d:e-f-g."; $count = $str =~ tr/,:;.-/,:;.-/;
Output: 4$str="1bus 2bus 3 bus 4 bus"; @count_arr = $str =~ s/bus/g; print(scalar(@count_arr));
Output: 7$str="a;b;c,d:e-f-g."; @count_arr = $str =~ /[,:;.-]+/g; print(scalar(@count_arr));
$count has the value 4$str = "1 -2 3 -5 8 13 -21 34 -53"; $count = 0; $count++ while ($str =~ /-\d+/g);
@arr = qw(1 -2 3 -5 8 13 -21 34 -53); @arr_new = grep { $_ < 0 } @arr; print("@arr_new: " . scalar(@arr_new)); # output: -2 -5 -21 -53: 4
Output: Positions of character 'i': 9 14 16 19 24 27 31 - Number of occurrences: 7$str="Supercalifragilisticexpialidocious"; push(@arr_pos, pos($str)) while ($str =~ /i/g); print("Positions letter i: @arr_pos \- Number of occurrences: " . scalar(@arr_pos) . "\n");
3. How to make a random string?
Maybe it's more clear to write:$str = ""; @chars = ('A'..'Z', 'a'..'z', '1'..'9', '!', '@', '#'); $str .= $chars[int(rand(@chars))] for (1 .. 8); print("$str\n"); # Output e.g eQa#B9j7
4. How to pad a string?
In Perl, you can use the
Here's an example of left-padding a string with spaces:' reinier'
Right-padding with a character:$original_string = "reinier"; $width = 10; # total length of the padded string $padded_string = sprintf("%${width}s", $original_string);# %${width}s equals %10s print "Padded String: '$padded_string'\n\n";# Output: ' reinier'
Center padding is rather tedious with$original_string = "reinier"; $padding_character = "*"; $padding_mode = "right"; ($padding_mode eq "left") ? ($padding_mode = "") : ($padding_mode = "-"); $width = 10; $padded_string = sprintf("%$padding_mode${width}s", $original_string); $padded_string =~ s/ /$padding_character/g; print("Padded String: '$padded_string'\n"); # Output: 'reinier***'
use Text::Padding; $pad = Text::Padding->new; $original_string = "reinier"; $padding_character = "$"; $width = 11; $padded_string = $pad->center( $original_string, $width ); $padded_string =~ s/ /$padding_character/g; print("Padded String: '$padded_string'\n"); # Output: '$$reinier$$'