What is the meaning of the dot in this open() usage in Perl?

Viewed 523

How can I understand the following usage of the open() function in Perl File I/O?

open(FHANDLE, ">" . $file )

I tried to find this type of syntax in the docs but did not find; please note there is a . (dot) after ">".

All I cannot understand is a use of dot, the rest I know.

2 Answers

This is an example of the old, two-argument form of open (which should be avoided now that three-argument open is available). In Perl, . is the append operator. It combines the two strings into a single string.

The line of code you posted is equivalent to open(FHANDLE, ">$file" ), it just uses a different method of combining the > and $file.

The better way to do it these days would be open(my $fhandle, '>', $file), as shown in the documentation you linked to.

This is the two-argument open. The dot . is the string concatenation operator in Perl. If open is called with two arguments, the second argument contains both the mode and the path.

In your case, it will open the file named in $file for writing.

However, for several reasons you should not do this. It's more common to use the three-argument-open, and the lexical filehandles instead of the global GLOB filehandle.

The lexical filehandle makes sure Perl implicitly closes the handel for you as soon as it goes out of scope. Using different args for mode and filename is a security concern, because otherwise a malicious user could smuggle in mode-changes into the filename.

open my $fh, '>', $file or die $!;

IN addition to the now lexical filehandle and the separation of the mode and the filename, we also check for errors in this code, which is always a good idea.

Related