Perl Notes 2

Files

 

Standard Files

STDIN

STDOUT

STDERR

 

To read Input from Keyboard

$

input = <STDIN>;

 

To read input from keyboard until Ctrl+D or Ctrl+Z is pressed

while (<STDIN>){    #input read to $_

        print();

}

 

To Remove the newline character at the end of line

$input = chomp(<STDIN>);


 

Diamond operator <> when no input provides look into ARGV array for the stream.

Read Multiple Files at a time

 

@ARGV = (“09lst01.pl”, “09lst02.pl”);

while (<>) {

print();

}

 

 

File Test Operators

 

Perl has many operators that you can use to test different aspects of a file. For example, you can use the -e operator to ensure that a file exists before deleting it. Or you can check that a file can be written to before appending to it. By checking the feasibility of the impending file operation, you can reduce the number of errors that you program will encounter

   

-e 

If file exists 

-z 

If file is zeo bytes 

-r 

If file is readable 

-w 

If file can be update/written

-x 

If file is an executable File 

   

-b 

If device is block device 

-c 

If device is character device 

-d 

If it is directory 

-l 

If it is symbolic link 

-p 

If it is pipe 

-s 

If it is Socket 

-t 

If OPERAND is a text file. If OPERAND is a file handle, then the current buffer is examined, instead of the file itself

-f

If it is Regular File and not Special file as above.

 

The OPERAND is either File Handle or File Name.

 

Eg:

If we want to process only regular files

foreach (@ARGV) {

next unless -f; # ignore all non-normal files.

print(“$_ is a Regular file.\n”);

}

 

 

The underscore file handle tells Perl to use the file information from the last system call

foreach (@ARGV){

    next unless -f;

    $size = -s _;

    print “$_ is $size long\n”;

}

 

File Functions

 

Display a File

$INPUT_FILE = “file1.csv”;

 

open(INPUT_FILE);

 

while(<INPUT_FILE>){

    print();

}

 

close(INPUT_FILE);

 

File Opening Modes

open(FILE_HANDLE, filename)

 

open(FILE_HANDLE, <filename)

Opens for reading

open(FILE_HANDLE, >filename)

Opens for writing

open(FILE_HANDLE, >>filename)

Opens for appending

open(FILE_HANDLE, +>filename)

Opens for both input and output

 

Printing a LogFile

if (open(LOGFILE, “>message.log”)) {

print LOGFILE (“This is message number 1.\n”);

print LOGFILE (“This is message number 2.\n”);

close(LOGFILE);

}

 

But problem here is when opened next time, previous content is lost

Hence use open(LOGFILE, “>>message.log”)

 

Binary Files

Reading a File to Show Text Mode Line Endings

$buffer = “”;

 

open(FILE, “<binary.dat”);

binmode(FILE);

read(FILE, $buffer, 20, 0); # 0 – 0th position in the file

close(FILE);

 

foreach (split(//, $buffer)) { #split each character/unit/byte

printf(“%02x “, ord($_)); #display first character of $_

print “\n” if $_ eq “\n”;

}

 

 

Table 9.3-Perl’s File Functions

Function

Description

binmode(FILE_HANDLE)

This DOS-based function puts FILE_HANDLE into a binary mode. For more information, see the section “Example: Binary Files” later in this chapter.

chdir(DIR_NAME)

Causes your program to use DIR_NAME as the current directory. It will return true if the change was successful, false if not.

chmod(MODE, FILE_LIST)

This UNIX-based function changes the permissions for a list of files. A count of the number of files whose permissions were changed is returned. There is no DOS equivalent for this function.

chown(UID, GID, FILE_LIST)

This UNIX-based function changes the owner and group for a list of files. A count of the number of files whose ownership were changed is returned. There is no DOS equivalent for this function.

close(FILE_HANDLE)

Closes the connection between your program and the file opened with FILE_HANDLE.

closedir(DIR_HANDLE)

Closes the connection between your program and the directory opened with DIR_HANDLE.

eof(FILE_HANDLE)

Returns true if the next read on FILE_HANDLE will result in hitting the end of the file or if the file is not open. If FILE_HANDLE is not specified the status of the last file read is returned. All input functions return the undefined value when the end of file is reached, so you’ll almost never need to use eof().

fcntl(FILE_HANDLE, FUNCTION, SCALAR)

Implements the fcntl() function which lets you perform various file control operations. Its use is beyond the scope of this book.

fileno(FILE_HANDLE)

Returns the file descriptor for the specified FILE_HANDLE.

flock(FILEHANDLE, OPERATION)

This UNIX-based function will place a lock on a file so that multiple users or programs can’t simultaneously use it. There is no DOS equivalent for this function. The flock() function is beyond the scope of this book.

getc(FILE_HANDLE)

Reads the next character from FILE_HANDLE. If FILE_HANDLE is not specified, a character will be read from STDIN.

glob(EXPRESSION)

Returns a list of files that match the specification of EXPRESSION, which can contain wildcards. For instance, glob(“*.pl”) will return a list of all Perl program files in the current directory.

ioctl(FILE_HANDLE, FUNCTION, SCALAR)

Implements the ioctl() function which lets you perform various file control operations. Its use is beyond the scope of this book. For more in-depth discussion of this function see Que’s Special Edition Using Perl for Web Programming.

link(OLD_FILE_NAME, NEW_FILE_NAME)

This UNIX-based function creates a new filename that is linked to the old filename. It returns true for success and false for failure. There is no DOS equivalent for this function.

lstat(FILE_HANDLE_OR_FILE_NAME)

Returns file statistics in a 13-element array. lstat() is identical to stat() except that it can also return information about symbolic links. See the section “Example: Getting File Statistics” for more information.

mkdir(DIR_NAME, MODE)

Creates a directory named DIR_NAME. If you try to create a sub-directory, the parent must already exist. This function returns false if the directory can’t be created. The special variable $! is assigned the error message.

open(FILE_HANDLE, EXPRESSION)

Creates a link between FILE_HANDLE and a file specified by EXPRESSION. See the section “Example: Opening Files” for more information.

opendir(DIR_HANDLE, DIR_NAME)

Creates a link between DIR_HANDLE and the directory specified by DIR_NAME. opendir() returns true if successful, false otherwise.

pipe(READ_HANDLE, WRITE_HANDLE)

Opens a pair of connected pipes like the corresponding system call. Its use is beyond the scope of this book. For more on this function see Que’s Special Edition Using Perl for Web Programming.

print FILE_HANDLE (LIST)

Sends a list of strings to FILE_HANDLE. If FILE_HANDLE is not specified, then STDOUT is used. See the section “Example: Printing Revisited” for more information.

printf FILE_HANDLE (FORMAT, LIST)

Sends a list of strings in a format specified by FORMAT to FILE_HANDLE. If FILE_HANDLE is not specified, then STDOUT is used. See the section “Example: Printing Revisited” for more information.

read(FILE_HANDLE, BUFFER, LENGTH, OFFSET)

Reads up to LENGTH bytes from FILE_HANDLE starting at OFFSET position in the file into the scalar variable called BUFFER. It returns the number of bytes read or the undefined value.

readdir(DIR_HANDLE)

Returns the next directory entry from DIR_HANDLE when used in a scalar context. If used in an array context, all of the file entries in DIR_HANDLE will be returned in a list. If there are no more entries to return, the undefined value or a null list will be returned depending on the context.

readlink(EXPRESSION)

This UNIX-based function returns that value of a symbolic link. If an error occurs, the undefined value is returned and the special variable $! is assigned the error message. The $_ special variable is used if EXPRESSION is not specified.

rename(OLD_FILE_NAME, NEW_FILE_NAME)

Changes the name of a file. You can use this function to change the directory where a file resides but not the disk drive or volume.

rewinddir(DIR_HANDLE)

Resets DIR_HANDLE so that the next readdir() starts at the beginning of the directory.

rmdir(DIR_NAME)

Deletes an empty directory. If the directory can be deleted it returns false and $! is assigned the error message. The $_ special variable is used if DIR_NAME is not specified.

seek(FILE_HANDLE, POSITION, WHENCE)

Moves to POSITION in the file connected to FILE_HANDLE. The WHENCE parameter determines if POSITION is an offset from the beginning of the file (WHENCE=0), the current position in the file (WHENCE=1), or the end of the file (WHENCE=2).

seekdir(DIR_HANDLE, POSITION)

Sets the current position for readdir(). POSITION must be a value returned by the telldir() function.

select(FILE_HANDLE)

Sets the default FILE_HANDLE for the write() and print() functions. It returns the currently selected file handle so that you may restore it if needed. You can see the section “Example: Printing Revisited” to see this function in action.

sprintf(FORMAT, LIST)

Returns a string whose format is specified by FORMAT.

stat(FILE_HANDLE_OR_FILE_NAME)

Returns file statistics in a 13-element array. See the section “Example: Getting File Statistics” for more information.

symlink(OLD_FILE_NAME, NEW_FILE_NAME)

This UNIX-based function creates a new filename symbolically linked to the old filename. It returns false if the NEW_FILE_NAME could not be created.

sysread(FILE_HANDLE, BUFFER, LENGTH, OFFSET)

Reads LENGTH bytes from FILE_HANDLE starting at OFFSET position in the file into the scalar variable called BUFFER. It returns the number of bytes read or the undefined value.

syswrite(FILE_HANDLE, BUFFER, LENGTH, OFFSET)

Writes LENGTH bytes from FILE_HANDLE starting at OFFSET position in the file into the scalar variable called BUFFER. It returns the number of bytes written or the undefined value.

tell(FILE_HANDLE)

Returns the current file position for FILE_HANDLE. If FILE_HANDLE is not specified, the file position for the last file read is returned.

telldir(DIR_HANDLE)

Returns the current position for DIR_HANDLE. The return value may be passed to seekdir() to access a particular location in a directory.

truncate(FILE_HANDLE, LENGTH)

Truncates the file opened on FILE_HANDLE to be LENGTH bytes long.

unlink(FILE_LIST)

Deletes a list of files. If FILE_LIST is not specified, then $_ will be used. It returns the number of files successfully deleted. Therefore, it returns false or 0 if no files were deleted.

utime(FILE_LIST)

This UNIX-based function changes the access and modification times on each file in FILE_LIST.

write(FILE_HANDLE)

Writes a formatted record to FILE_HANDLE. See chapter 11, “Creating Reports,” for more information.

Advertisements

About wikihead

A Seeker. Information Security Professional, Pursuing Life with Ayurveda.
This entry was posted in Notes, Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s