These classnotes are depreciated. As of 2005, I no longer teach the classes. Notes will remain online for legacy purposes

UNIX01/Common Perl Commands II

Classnotes | UNIX01 | RecentChanges | Preferences

Difference (from prior major revision) (no other diffs)

Removed: 35,39d34

Regular Expression Matching




One thing we've mentionned briefly before without really exploring is Regular Expression Matching. This is a concept that is key to using many UNIX applications, but is unfortunately a very rich and deep subject. As such, if you continue to take these UNIX courses, you will explore it more and more as the classes progress. For now, we will only concern ourselves with the most basic matching which we will use today. If you would like to immerse yourself in Perl's Regular Expressions, then I would recommend reading this document: http://www.perldoc.com/perl5.6/pod/perlre.html


Files and I/O

open

The open command can be used to open a file. The basic syntax is
 open ( ID, "filename" );

where ID is the ID assigned to the I/O stream.

But how do we tell whether the file is openned for reading, writing, appending, etc? We do so through the use of pipes (as we have been looking at since day one).

By default, open will open a file to read:

 open ( ID, "some_file.txt" );

This is equivalent if we used the pipe redirect:

 open ( ID, "<some_file.txt" );

If we wish to open a file for writing, we use the pipe redirect into the file:

 open ( ID, ">some_file.txt" );

If we wish to append to a file (instead of overwriting it), we would use double pipe redirect:

 open ( ID, ">>some_file.txt");

close

When we are finished with a file handle (I/O stream), we should close it:
 close ID;

Reading data from a file

There are a number of ways to get data from a file. The most direct way (and the only way we will focus on in this class) is to simply pass the contents from the file handle into a variable (usually an array). If I wanted to take the contents of an I/O stream called "ID" and place them into the variable $a, I would use:
 $a = <ID>;

A full sequence where we openned a file, read from it, and closed it would look like the following:

 open ( ID, "some_file.dat" );
 $data = <ID>;
 close ID;


Classnotes | UNIX01 | RecentChanges | Preferences
This page is read-only | View other revisions
Last edited July 26, 2003 3:46 am (diff)
Search:
(C) Copyright 2003 Samuel Hart
Creative Commons License
This work is licensed under a Creative Commons License.