1. Perl
  2. builtin functions
  3. here

open function - opens a file

To open a file , use the open function . The first argument is a variable for assigning the got file handle, the second argument is open mode, and the third argument is the file name. Returns true if the file was opened successfully, false if it failed.

$ret = open($fh, $mode, $file);

When opening a file, the following is a common way to write it. Learn other ways based on this.

open(my $fh, "<", $file)
  or die "Can't open $file:$!";

"<" Means open mode, and when reading a file, specify "<".

Commonly used open mode

Open mode Symbol
Read <
write in >
Additional writing >> >>

Specify in the second argument of the open function. Enclose it in double or single quotes and pass it as a string.

Read mode <

Read mode is a mode in which a file is opened read-only. If the file does not exist, an error will occur.

Write mode>

Write mode is a mode in which a file is opened write-only. The contents of the original file are deleted the moment you open it. If the file does not exist, it will be created.

Additional write mode >>

The additional write mode is a mode in which a file is opened exclusively for additional write, and writing starts from the end of the current file. If the file does not exist, it will be created.

What if you want to read a file and write to it?

There is another read/write mode in the file open mode, but this mode is not used for general purposes. It's easy to think that read-write mode is used when reading a file and writing to that file, but it's different.

As I will explain in detail later, this method is extremely dangerous. To do it safely, follow the steps below.

  1. Read the file.
  2. Write all lines containing changes to a temporary file.
  3. Delete the original file.
  4. Rename the temporary file to the original file name.

Exception handling

When you open the file, you also need to handle the exception. If the file fails to open, there is no point in moving on to the subsequent processing, so use the die function to terminate the program. The cause of the file opening failure is assigned to "$!", So include that in the error message as well.

open(my $fh, "<", $file)
  or die "Can't open $file:$!";

Open two arguments - not recommended

Older source code may use a two-argument open function, but now it is recommended to use a three-argument open function.

# 2 Argument open function is deprecated
open($fh, "<$file");

Example

This is an example file open using the open function.

use strict;
use warnings;

# Pass the name of an existing file as an argument.
my $file = shift;

open(my $fh2, "<", $file)
  or die "Can't open file $file:$!";

Related articles

Related Informatrion