www.fromthevalley.com.au

Read a File Perl

Opening the File

Within our script, we will want to read the data into our script. In order to do so, we must first open the file. We do this with a command like this:

open(HANDLE, "FileName/Location");

The HANDLE above is something you will use to reference the file when you read from it and when you close it. The FileName/Location is the actual location of the file. Since we will have them in the same directory, we can just use the filename. If you have it in another directory, use the server path to the file. Here is how we can open our file:

open(DAT, "wrestledata.cgi");

Of course, you may want to assign the filename to a variable, so you could change it later more easily if you need to:

$data_file="wrestledata.cgi";
open(DAT, $data_file);

One last bit on the opening of the file. You may want to have an option to show an error if the file cannot be opened. So, we can add the "die" option to print the error to standard output. What we will do is use the open command, give the "or" option (two pipe symbols) and use the "die" routine as the option:

$data_file="wrestledata.cgi";
open(DAT, $data_file) || die("Could not open file!");

Reading the File

Now we are able to read from the open file. The easiest way to do this is to just assign the contents of the file to an array:

$data_file="wrestledata.cgi";
open(DAT, $data_file) || die("Could not open file!");
@raw_data=<DAT>;

This will take everything from the file and toss it into the @raw_data array. Notice the use of the DAT handle for reading, with the < and > around it. We can then use the array to grab the information later, so that we can go ahead and close the file.

Close the File!

We have to be sure to remember to close the file when we are done with it, so we close it with the close command:

close(DAT);

Again, the DAT handle is used to reference the file and close it. So now we have:

$data_file="wrestledata.cgi";
open(DAT, $data_file) || die("Could not open file!");
@raw_data=<DAT>;
close(DAT);

 

 

Read in line by line:

    my $data_file="/mnt/mount_A/INPUT";
    open(DAT, $data_file) || die("Could not open file!");
    while(<DAT>){

            chomp($_);
            my @data = split(/\|/,$_);
   }

   close(DAT);

HOMEAJAXAPACHEBizphoneCSSDNSGeneralGraphicsHTMLHardwareJavascriptLinuxMACMS SQLMailMicrosoftOFFICE 365PerlPostgresSEOSocial MediaVMwareWindows 10