Open In App

Perl | Opening and Reading a File

Last Updated : 26 Feb, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

A filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle.
 

Opening a File

 
Open function is used to open a new file or an existing file.

Syntax: open FILEHANDLE, VAR

Here FILEHANDLE is the handle returned by the open function and VAR is the expression having file name and mode of opening the file.
The table given below shows the modes in which file can be opened and access to various operations.

Mode Description
r or < Read Only Access
w or > Creates, Writes, and Truncates
a or >> Writes, Appends, and Creates
r+ or +< Reads and Writes
w+ or +> Reads, Writes, Creates, and Truncates
a+ or +>> Reads, Writes, Appends, and Creates


 

Reading a file

 
Once a FILEHANDLE is assigned a file, various operations like reading, writing and appending can be done. There are a number of different ways of reading a file.

  • Using a File Handle Operator
  • Using getc function
  • Using read function
  • The FileHandle Operator
    The main method of reading the information from an open filehandle is using the operator < >. When < > operator is used in a list context, it returns a list of lines from the specified filehandle. The example below reads one line from the file and stores it in the scalar.

    Let the content of file “GFG.txt” is as given below:

    GeeksforGeeks
    Hello Geek
    Geek a revolution
    Geeks are the best
    

    Example: GFG.pl




    # Opening the file 
    open(fh, "GFG.txt") or die "File '$filename' can't be opened";
      
    # Reading First line from the file
    $firstline = <fh>;
    print "$firstline\n";

    
    

    Output :

  • getc Function
    The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified

    Syntax: getc FILEHANDLE




    # Opening the file 
    open(fh, "GFG.txt") or die "File '$filename' can't be opened";
       
    # Reading First char from the file
    $firstchar = getc(fh);
    print "$firstchar\n";

    
    

    Output:

    If there was an error or the filehandle is at end of the file, then it returns undef.

  • read Function
    The read function is used to read binary data from a file using filehandle.

    Syntax
    read FILEHANDLE, SCALAR, LENGTH, OFFSET
    read FILEHANDLE, SCALAR, LENGTH

    Here, LENGTH represents the length of data to be read and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise, data is placed after bytes of OFFSET in SCALAR. On the success of file reading, the function returns the number of bytes read, zero at end of file, or undef if there was an error.

  •  

    Reading Multiple line at a time

     
    The example shown below reads the content of file specified by filehandle till it reaches End Of File(EOF).

    Example: File.pl




    # Opening the file
    open(FH, "GFG.txt")or die "Sorry!! couldn't open";
    print "Reading file \n";
      
    # Reading the file till FH reaches EOF
    while(<FH>)
    {
        # Printing one line at a time
        print $_;
    }
    close;

    
    

    Output :

     

    Exception Handling in Files

     
    There are two ways in which Exception can be handled

    • Throw an exception if file cannot be opened
    • Give a warning if file cannot be opened and continue running
    • Throw an Exception
      When filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program.
      Example :




      # Initializing filename 
      $filename = 'GFG1.txt';
        
      # Prints an error and exits if file not found
      open(fh, '<', $filename) or die "Couldn't Open file $filename";

      
      

      Output:

      The above code prints an error if file not found and exits from the code.

    • Give a warning
      When filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running.
      Example :




      # Initializing filename
      $filename = 'GFG.txt';
      # Opening a file and reading content
      if(open(fh, '<', $filename))
      {
          while(<fh>)
          {
              print $_;
          }
      }
        
      # Executes if file not found
      else
      {
        warn "Couldn't Open a file $filename";
      }

      
      

      Output:



      Like Article
      Suggest improvement
      Previous
      Next
      Share your thoughts in the comments

Similar Reads