What does dot-equals mean in Perl?

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.

Answers


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.


You have found the string concatenation operator.

Let's try it :

my $string = "foo";

$string .= "bar";

print $string;
foobar

This performs concatenation to the $input var. Whatever is coming in via STDIN is being assigned to $input.


Need Your Help

Save and render a webpage with PhantomJS and node.js

javascript html node.js web-scraping phantomjs

I'm looking for an example of requesting a webpage, waiting for the JavaScript to render (JavaScript modifies the DOM), and then grabbing the HTML of the page.