This is simplified using open().
Usage: open(FILEHANDLE, accessMode_with_fileName)
FILEHANDLE is like a pointer to the file's contents.
accessMode_with_fileName is actually composed of two i.e.
1. Access Mode: that specifies how you wan to access the file. It can be
a. Read, where you can just read from the file
b. Write, where you can just write to the file
c. Append, where you can write to the end of the file
What you use depends on the requirement. To specify one of these modes you need to use any of these symbols : < (read), > (write) & >> (append). If you open a file without any of these symbols, it will default to read mode.
You can put a '+' in front of the '>' or '<' to indicate that you want both read and write access to the file (I have not used that, pretty much).
2. Filename: The second component is the filename itself. so if you want to open a file (say /home/vik/foo) for reading the open call looks like:
open (FILE, "</home/vik/foo");
or
open (FILE, "/home/vik/foo"); ## NO Access mode symbol is by default read mode
The same example holds good for all other modes, you have to just change the access mode symbol as per requirement.
The return value of open() is undef if it cannot open the file, so this check can be put using 'or', like this:
open (FILE, "</home/vik/foo") or die "Could not open file for reading: $!\n";
Here $! is a special variable that holds the error.
Reading/Writing using the file handle
After opening the file for reading, you can access the files' contents using a scalar variable / an array. Here are the examples:
1. Using a scalar: If you want to read a file line by line, use a scalar variable like this,
my $files_line = <FILE>;
Remember this always, when you read a line from the file the '\n' (newline character) will be at the end of the read contents, so use chomp() to remove any newline characters.
So the example becomes:
my $files_line = <FILE>;
chomp $files_lines;
2. Using an array:
If you want to read all the lines of a file, you use the array. See this example below:
my @files_contents = <FILE>;
With the chomp:
my @files_contents = <FILE>;
chomp(@files_contents);
Writing to a file
Use print to write to a file. See this example:
print FILE "I want to be in a file\n"
Subscribe to:
Post Comments (Atom)



0 comments:
Post a Comment