Open In App

Perl | eof – End of File Function

Improve
Improve
Like Article
Like
Save
Share
Report

The eof() function is used to check if the End Of File (EOF) is reached. It returns 1 if EOF is reached or if the FileHandle is not open and undef in all other cases.

Syntax: eof(FileHandle)

Parameter:
FileHandle: used to open the file

Returns: 1 if EOF is reached

Cases:

  1. eof(FileHandle) : Passing FileHandle to eof() function. If File is empty then it returns 1 otherwise undef.
    Example:




    #!/usr/bin/perl
      
    # Opening Hello.txt file
    open(fh,"<Hello.txt"); 
       
    # Checking if File is Empty or not
    if(eof(fh)) # Returns 1 if file is empty 
                # i.e. EOF encountered at the beginning
    {
        print("End Of File\n");
    }
      
    # Closing the File
    close(fh);
      
    # Checking if File is closed or not
    # using eof() function
    if(eof(fh)) # fh is a closed file 
                # and hence, eof returns 1
    {
        print("File is closed");
    }

    
    

    Output :

    • If Hello.txt is empty:
    • If ex1.txt is not empty:
  2. eof() : The eof with empty parentheses refers to pseudo file formed from the files passed as command line arguments and is accessed via the ‘<>’ operator. eof() checks for the end of the last file of all the files passed as arguments in the command line.

    Example:




    #!/usr/bin/perl
      
    # opens filehandle for files passed as arguments
    while(<>)
    {
        # checks for eof of the last file passed as argument
        if(eof()) # It returns 1 if End Of the File is reached.
        {
            print "$_";
            print("\nEnd Of File Reached");
        }
       
           
        else # prints each fileread of the File
        {
            print "$_";
        }
    }

    
    

    Output :

  3. eof : eof with no parentheses checks for the End Of File of the last file read.

    Example:




    #!/usr/bin/perl
      
    # opening Hello.plx
    if(!open(fh, "<Hello.txt"))
    {
        print("File Not Found");
        exit;
    }
      
    if(eof fh)
    {
        print("Empty File");
        exit;
    }
      
    # check for End Of File of last file read i.e. fh
    if(not eof) # Returns 1 since eof is not reached
    {
        print("End Of File Not Reached");
    }
      
    # Empty while loop to reach to the End Of File
    while(<fh>) 
    { };
      
    # check for End Of File of last file read i.e. fh
    if(eof) # Returns 1 since eof is reached
    {
        print("\nEnd Of File Reached");
    }

    
    

    Output :
    End of file



Last Updated : 17 Dec, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads