Perl - File

perl

How can we open a file for reading?

#!/usr/bin/perl 
use strict;
use warnings;
use IO::File ();
my $fh = IO::File->new();
if ($fh->open("<$filename")) {
    // Notice the < sign is being passed as part of the file name to open()
    // Do something interesting
} else {
    die("Unable to open $filename for reading.");
}

How can we open a file for writing?

#!/usr/bin/perl 
use strict;
use warnings;
use IO::File ();
my $fh = IO::File->new();
if ($fh->open(">$filename")) {
    // Notice the > sign is being passed as part of the file name to open()
    // Do something interesting
} else {
    die("Unable to open $filename for reading.");
}

How can we open a file for appending?

#!/usr/bin/perl 
use strict;
use warnings;
use IO::File ();
my $fh = IO::File->new();
if ($fh->open(">>$filename")) {
    // Notice the double > sign is being passed as part of the file name to open()
    // Do something interesting
} else {
    die("Unable to open $filename for appending.");
}

How can we work with files without using IO::File?

open (MYFILE, '<SJC_AD_File.txt');            // Open the file for reading
open (OUTFILE, '>>UnableToAuthenticate.txt');    // Open the file for appending
<MYFILE>;    // Read in a line and store it in $_ but in this case, we ignore it.
while (<MYFILE>) {
     chomp;
    $cnt = $cnt + 1;
    $line = $_;
    if (! testAuthentication($line)) {
        print OUTFILE $line, "\n";                // Write to the file
        $failureCnt = $failureCnt + 1;
    } else {
        $successCnt = $successCnt + 1;
    }
}
close (MYFILE); 
close (OUTFILE);

while ($name = <FH>) { ... }
$name = <STDIN>

How can we read a line from a file?

my $line = <$fh>;

while (defined($_ = $io->getline)) { ... }

You can use $fh in places where you typically use the STDIN file handle

How can we write a line to a file?

print $fh "Something";

You can use $fh in places where you typically use the STDOUT file handle

How can we create a reference to a file handle?

It is not possible to create a reference to a file handle or directory handle directly via the \ notation. However, you can create reference to file handle, directory handle, or a socket like this:

$ioref = *STDIN{IO};

How can we pass a reference to a file handle, a directory handle, or a socket?

\*STDIN

How can we use opendir, readdir, and closedir?

opendir(DIRHANDLE, $dirname) || die("Cannot open directory $dirname);
while (defined($entry = readdir(DIRHANDLE)) {
    if (-f "$dirname/$entry") { ... }
}
closedir(DIRHANDLE);

Other commands:

opendir DIRHANDLE, EXPR    // open directory EXPR, associating it with DIRHANDLE
                    // returns 0 on failure

readdir DIRHANDLE    // In scalar context, returns the next directory entry.
                // In list context, returns the remaining entries

rewinddir DIRHANDLE    // set the current position within the directory specified
                // by DIRHANDLE to the beginning of directory

telldir DIRHANDLE    // returns the current position within directory listing
                // referred to by DIRHANDLE.  Return integer.

seekdir DIRHANDLE, POS    // set the current position with DIRHANDLE to POS
                    // the value of POS must be a value returned by telldir

glob("filename*")    // In list context, returns a list of names that match the argument.
                // In scalar context, returns the next name that match
open(WORDLIST, "wordlist");
$name = <WORDLIST>;
close(WORDLIST);

if (-M WORDLIST >= 7.0) die "Sorry.  wordlist is older than seven days.";

open(INF, "<filename") || die("Cannot open file");
open(OUTF, ">filename") || die("$!");
open(APP, ">>filename");
close(FILEHANDLE)

-r    readable
-w    writable
-x    executable
-o    own by the user
-e    exist
-z    has zero length
-s    exists and has zero length
-f    is a file
-d    is a directory
-l    is a symbolic link
-S    is a socket
-p    is a pipe
-b    is a block file
-c    is a character file
-T    is a text file
-B    is a binary file
-M    Number of days (modification age)
-A    Number of days (access age)
-C    Number of days (inode modification age)

@status = stat("filename");
0    Device number
1    Inode number
2    Mode
3    Number of links
4    User ID
5    Group ID
6    Device number referred to
7    Size in bytes
8    Time of last access
9    Time of last modification
10    Time of status change
11    Proffered block size
12    Actual number of blocks (a block size is 512 bytes)

link("file1","file2")    // create file2 and link it to file1
readlink("filez");
symlink("file1","file2");
unlink("file1");
unlink LIST
rename("file1","file2");
chmod(0777,"file1","file2");
chmod MODE LIST
chown(UID,GID,"file1","filez");
chown UID,GID,LIST;
atime ATIME, MTIME, LIST;        // set access and modification time
utime(accesstime, modificationtime, "file1", "filez");

opendir(D,"directory1");
closedir(D);
readdir(D)
rewinddir(D);
telldir(D)    // returns the current position
seekdir(D,n)
mkdir("dir1",0777)
rmdir("dir1");
chdir("dir1")
glob("file*")    // In list context, list of name that match the argument.
            // In scalar context, returns the next name that match
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License