Perl has two different string operators-the concatenation (.) operator and the repetition (x) operator. These operators make it easy to manipulate strings in certain ways. Let's start with the concatenation operator. Strings can be concatenated by the . operator.
$first_name = "David"; $last_name = "Marshall"; $full_name = $first_name . " " . $last_name;
we need the " " to insert a space between the strings.
Strings can be repeated with tt x operator
$first_name = "David"; $david_cubed = $first_name x 3;
which gives "DavidDavidDavid".
String can be referenced inside strings
$first_name = "David"; $str = "My name is: $first_name";
which gives "My name is: David".
Conversion between numbers and Strings
This is a useful facility in Perl. Scalar variables are converted automatically to string and number values according to context.
Thus you can do
$x = "40"; $y = "11"; $z = $x + $y; # answer 51 $w = $x . $y; # answer "4011"
Note if a string contains any trailing non-number characters they will be ignored.
i.e. " 123.45abc" would get converted to 123.45 for numeric work.
If no number is present in a string it is converted to 0.
The chop() operator
chop() is a useful operator which takes a single argument (within parenthesis) and simply removes the last character from the string. The new string is returned (overwritten) to the input string.
chop('suey') would give the result 'sue'
Why is this useful?
Most strings input in Perl will end with a
\n. If we want to string
operations for output formatting and many other processed then the
\n might be inappropriate. chop() can easily remove this.
Many other applications find chop() useful