Monday, July 30, 2007

Basic I/O (Part 4)-- Perl Study Notes

Basic I/O (Part 4)-- Perl Study Notes

<STDIN>
while (defined($line = <STDIN>))
{
... # process $line here
}

Diamond Operator
a. The diamond operator gets its data form file or files specified on the command line that invoked the Perl program

for example, we have a pl file readfile.pl as below
#!/usr/bin/perl
while (<>)
{
print $_;
}
run the perl like this
readfile.pl file1 file2 file3
the diamond operator reads each line of file 1 and file2 and file3
b. In a scalar context, it returns a single line. In a list/array context, it returns all lines.
c. The daimond operator gets the files form the @ARGV. @ARGV is initiated by the parameters of the command line.The parameter can be assigned in the program itsefl. Here is the example,

#!/usr/bin/perl
@ARGV=qw(file1,file2,file3)
while (<>)
{
print $_;
}

<STDOUT>
print (2+3),"hello"; # wrong! prints 5, ignores "hello"
print ((2+3),"hello"); # right, prints 5hello
print 2+3,"hello"; # also right, prints 5hello


Filehanlers
open (FILEHANDLE,$filewanttoopen); #open external file or device $filewanttoopen, return true if success and false if fail
open FILEHANDLE, ">$filewanttowrite); # open the file $filewanttowrite to write, return true if success and false if fail
open FILEHANDLE, ">>$filewanttoappend); # open the file $filewanttoappend for appending, return true if success and false if fail
close(FILEHANDLE); #close the FILEHANDLER

Pls note reopen the FILEHANDLE can close it automatically.


die and warn
die("This is the error message!!!"); # print out "This is the error message!!!" followed the program name and line number and exit the perl.
die("This is the error message!!!\n"); # just print out "This is the error message!!!" followed the program name and line number and exit the perl.
warn("This is the error message!!!"); # just print out the string "This is the error message!!!" without terminate the perl

#!c:\perl\bin\perl.exe
# here is the example to copy file $a to $b
open(IN,$a) die "cannot open $a for reading: $!";
open(OUT,">$b") die "cannot create $b: $!";
while () { # read a line from file $a into $_
print OUT $_; # print that line to file $b
}
close(IN) die "can't close $a: $!";
close(OUT) die "can't close $b: $!";


File tests operator (Most used)
-e $filename; return true if $filename is existing while false if not.
-r $filename; return true if $filename is readable while false if not.
-w $filename; return true if $filename is writable while false if not.
-x $filename; return true if $filename is executable while false if not.
-s $filename; return size of the $filename if $filename is existing.
-M $filename; return days since the $filename is last modified.
-A $filename; return days since the $filename is last accessed.
-C $filename; return days since the inode of the $filename changes.

No comments: