What does ".=" mean in Perl (dot-equals)? Example code below (in the while clause):
if( my $file = shift @ARGV ) { $parser->parse( Source => {SystemId => $file} ); } else { my $input = ""; while( <STDIN> ) { $input .= $_; } $parser->parse( Source => {String => $input} ); } exit;
Thanks for any insight.
The period .
is the concatenation operator. The equal sign to the right means that this is an assignment operator, like in C.
For example:
$input .= $_;
Does the same as
$input = $input . $_;
However, there's also some perl magic in this, for example this removes the need to initialize a variable to avoid "uninitialized" warnings. Try the difference:
perl -we 'my $x; $x = $x + 1' # Use of uninitialized value in addition ... perl -we 'my $x; $x += 1' # no warning
This means that the line in your code:
my $input = "";
Is quite redundant. Albeit some people might find it comforting.
For pretty much any binary operator X
, $a X= $b
is equivalent to $a = $a X $b
. The dot .
is a string concatenation operator; thus, $a .= $b
means "stick $b
at the end of $a
".
In your code, you start with an empty $input
, then repeatedly read a line and append it to $input
until there's no lines left. You should end up with the entire file as the contents of $input
, one line at a time.
It should be equivalent to the loopless
local $/; $input = <STDIN>;
(define line separator as a non-defined character, then read until the "end of line" that never comes).
EDIT: Changed according to TLP's comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With