- Assignment Operators
- Increment and Decrement Operators
- String Concatenation and Repetition
- Operator Precedence and Associativity
- Using Patterns to Match Digits
- An Example: Simple Statistics
- Input and Output
- Another Example: Stocks
- A Note About Using Functions
- Going Deeper
String Concatenation and Repetition
String and text management is one of Perl's biggest strengths, and quite a lot of the examples throughout this book are going to involve working with stringsfinding things in them, changing things in them, getting them from files and from the keyboard, and sending them to the screen, to files, or over a network to a Web browser. Today, we started by talking about strings in general terms.
There are just a couple more things I want to mention about strings here, however, because they fit in with today's "All Operators, All the Time" theme. Perl has two operators for using strings: . (dot) for string concatenation, and x for string repetition.
To concatenate together two strings you use the . operator, like this:
'four score' . ' and seven years ago';
This expression results in a third string containing 'four score and seven years ago.' It does not modify either of the original strings.
You can put together multiple concatenations, and they'll result in one single long string:
'this, ' . 'that, ' . 'and the ' . 'other thing.'
Perl also includes a concatenate-and-assign shorthand operator; similar to the operators I listed in Table 3.1:
$x .= "dog";
In this example, if $x contained the string "mad", then after this statement $x would contain the string "maddog". As with the other shorthand assignment operators, $x .= 'foo' is equivalent to $x = $x . 'foo'.
The other string-related operator is the x operator (not the X operator; it must be a lowercase x). The x operator takes a string on one side and a number on the other (but will convert them as needed), and then creates a new string with the old string repeated the number of times given on the right. Some examples:
'blah' x 4; # 'blahblahblahblah' '*' x 3; # '***' 10 x 5; # '1010101010'
In that last example, the number 10 is converted to the string '10', and then repeated five times.
Why is this useful? Consider having to pad a screen layout to include a certain number of spaces or filler characters, where the width of that layout can vary. Or consider, perhaps, doing some kind of ASCII art where the repetition of characters can produce specific patterns (hey, this is Perl, you're allowedno, encouragedto do weird stuff like that). At any rate, should you ever need to repeat a string, the x operator can do it for you.