Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does dot-equals mean in Perl?

Tags:

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.

like image 779
Ted Kreutzer Avatar asked Jan 21 '13 17:01

Ted Kreutzer


2 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.

like image 70
TLP Avatar answered Oct 12 '22 19:10

TLP


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.

like image 42
Amadan Avatar answered Oct 12 '22 20:10

Amadan