Perl | Opening and Reading a File - GeeksforGeeks

26 Feb, 2019
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. 
 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.
 
 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 OperatorThe 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 :
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 FunctionThe getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specifiedSyntax: 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.
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 FunctionThe read function is used to read binary data from a file using filehandle.Syntaxread FILEHANDLE, SCALAR, LENGTH, OFFSETread FILEHANDLE, SCALAR, LENGTHHere, 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 fileopen(FH, "GFG.txt")or die "Sorry!! couldn't open";print "Reading file \n";  # Reading the file till FH reaches EOFwhile(<FH>){    # Printing one line at a time    print $_;}close;Output : Exception Handling in Files There are two ways in which Exception can be handledThrow an exception if file cannot be openedGive a warning if file cannot be opened and continue runningThrow an ExceptionWhen 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 foundopen(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 warningWhen 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 contentif(open(fh, '<', $filename)){    while(<fh>)    {        print $_;    }}  # Executes if file not foundelse{  warn "Couldn't Open a file $filename";}Output:My Personal Notes
arrow_drop_upSave
Syntaxread FILEHANDLE, SCALAR, LENGTH, OFFSETread 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.
 
 The example shown below reads the content of file specified by filehandle till it reaches End Of File(EOF).
Example: File.pl
# Opening the fileopen(FH, "GFG.txt")or die "Sorry!! couldn't open";print "Reading file \n";  # Reading the file till FH reaches EOFwhile(<FH>){    # Printing one line at a time    print $_;}close;
Output : 
 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 ExceptionWhen 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 foundopen(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.
# Initializing filename $filename = 'GFG1.txt';  # Prints an error and exits if file not foundopen(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 warningWhen 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 contentif(open(fh, '<', $filename)){    while(<fh>)    {        print $_;    }}  # Executes if file not foundelse{  warn "Couldn't Open a file $filename";}Output:My Personal Notes
arrow_drop_upSave
# Initializing filename$filename = 'GFG.txt';# Opening a file and reading contentif(open(fh, '<', $filename)){    while(<fh>)    {        print $_;    }}  # Executes if file not foundelse{  warn "Couldn't Open a file $filename";}
Output:
Perl-files
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | split() Function
Perl | push() Function
Perl | exists() Function
Perl | length() Function
Perl | chomp() Function
Perl | grep() Function
Perl | Regex Cheat Sheet
Perl | sleep() Function
Perl | Removing leading and trailing white spaces (trim)
Perl Tutorial - Learn Perl With Examples