Home / code / cgi

Working with files

Perl can work well with Files. There are several functions for working with files. The 2 basic functions are open and close. In the below example, the file c:\text.txt is assigned to the filehandle DATA. The file is opened and the first line is read and stored in $line.

open (DATA, "c:\\text.txt");

$line = <DATA>;

print &line;

close (DATA);
Important is that, when you work with files, the meaning of backslash is destroyed. You can do this with the following:
open (DATA, "c:\\text.txt");

open (DATA, 'c:\text.txt');

open (DATA, "c:/text.txt");
If you assign the filehandle to a array the entire file is printed.
open (DATA, "c:\\text.txt");

@lines = <DATA>;

print @lines;

close (DATA);

You can also write in a file. You do this with placing a special sign in front of the file. For writting this >, for adding to a file >>

In the following example a name is requested, that is then added to a file.

print "Please, enter you're name:";

chomp ($name=<STDIN>);

open (DATA, ">>c:\\text.txt") || die "Cannot open c:\\text.txt: $! \n";

print DATA "$name \n";

close (DATA);

print "You're now on the black list! \n";
In the last example a file is assigned to the variable $file. Then the file is opened for reading the lines.
$file="c:\\text.txt";

open (DATA, $file) || die "Cannot open $file: $! \n";

while (<DATA>)
{
  print "Line $. is: $_";
}

close (DATA);

 

TOP

Latest script:

 

Books: