Cyber Sentry
Application Development
System Architecture Design
Technical Due Diligence
Qmail Support and Consultancy
Scripting Help
Partners
Client Testimonials
Help Sections
Software Patents
Site Map
Contact us
Community
Home

File handling

Here is the basic perl program which does the same as the UNIX cat command on a certain file.

 

#!/usr/local/bin/perl

#

# Program tothe password file, read it in,

# print it, and close it again.

 

$file = '/etc/passwd'; # Name the file

INFO, $file); #the file

@lines = <INFO>; # Read it into an array

close(INFO); # Close the file

print @lines; # Print the array

 

Thefunction a file for input (i.e. for reading). The first parameter is the filehandle which allows Perl to refer to the file in future. The second parameter is an expression denoting the filename. If the filename was given in quotes then it is taken literally without shell expansion. So the expression '~/notes/todolist' will not be interpreted successfully. If you want to force shell expansion then use angled brackets: that is, use <~/notes/todolist> instead.

 

The close function tells Perl to finish with that file.

 

There are a few useful points to add to this discussion on filehandling. First, thestatement can also specify a file for output and for appending as well as for input. To do this, prefix the filename with a > for output and a >> for appending:

 

INFO, $file); #for input

INFO, ">$file"); #for output

INFO, ">>$file"); #for appending

INFO, "<$file"); # Alsofor input

 

Second, if you want to print something to a file you've alreadyd for output then you can use the print statement with an extra parameter. To print a string to the file with the INFO filehandle use

 

print INFO "This line goes to the file.\n";

 

Third, you can use the following tothe standard input (usually the keyboard) and standard output (usually the screen) respectively:

 

INFO, '-'); #standard input

INFO, '>-'); #standard output

 

In the above program the information is read from a file. The file is the INFO file and to read from it Perl uses angled brackets. So the statement

 

@lines = <INFO>;

 

reads the file denoted by the filehandle into the array Note that the <INFO> expression reads in the file entirely in one go. This because the reading takes place in the context of an array variable. If @lines is replaced by the scalar $lines then only the next one line would be read in. In either case each line is stored complete with its newline character at the end.



Qmail Help Section
Perl Tutorial
Linux Command Line Help
Top top Copyright Cyber Sentry Ltd  

Cyber Sentry -- Application Development Sitemap 1 2 3