PERL - Simple PERL scripts to do the following: 4. Write a program that reads in
ID: 3808760 • Letter: P
Question
PERL - Simple PERL scripts to do the following:
4. Write a program that reads in a file (pick any file from the directory) and display the contents of that file, line by line. Make sure the end of file is handled properly, and remember to close the filehandle after you are finished. Prompt the user for the filename to be read.
5. Modify the last program you wrote to incorporate the die statement to handle file open errors. You can use a custom message if you want.
6. Write a program that creates a file called data.dat in the current directory. Prompt the user for five numbers, and write them, one at a time, on both the screen and into the file. Close the file, then open it again for reading only, and display the contents on the screen. Handle error conditions that may occur.
Explanation / Answer
Question:4
Perl script is given as follows:
#!/usr/bin/perl
use warnings;
use strict;
my $nameOfFile = 'c: st.txt';
open(FileHandler, '<', $nameOfFile) or die $!;
while(<FileHandler>){
print $_;
}
close(FileHandler);
Script explanation:
Here in this script we have used "open()" function to open the file for reading. Then we have used while loop where we read a line from the file and then assign that line to the variable $_ . And when the end of the file is reached then the loop got terminated. Then we are printing the line.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.