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 to open the password file, read it in, # print it, and close it again. $file = '/etc/passwd'; open(INFO, $file); @lines = <INFO>; close(INFO); print @lines; # # # # # Name the file Open the file Read it into an array Close the file Print the array

The open function opens 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, the open statement 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:
open(INFO, open(INFO, open(INFO, open(INFO, $file); ">$file"); ">>$file"); "<$file"); # # # # Open Open Open Also for input for output for appending open for input

Second, if you want to print something to a file you've already opened 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 to open the standard input (usually the keyboard) and standard output (usually the screen) respectively:
open(INFO, '-'); open(INFO, '>-'); # Open standard input # Open 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

This because the reading takes place in the context of an array variable. This has the form foreach $morsel (@food) { print "$morsel\n". The first time through the block $morsel is assigned the value of the first item in the array @food.@lines = <INFO>. In Perl any non-zero number and non-empty string is counted as true. In either case each line is stored complete with its newline character at the end. but are very similar to Pascal. foreach To go through each line of an array or other list-like structure (such as lines in a file) Perl uses the foreach structure. Next time it is assigned the value of the second item. too. $a == $b $a != $b $a eq $b $a ne $b # # # # # Is $a numerically equal to $b? Beware: Don't use the = operator. If @lines is replaced by the scalar $lines then only the next one line would be read in. zero by itself in a string. print "Yum yum\n". Here are some tests on numbers and strings. Testing The next few structures rely on a test being true or false. The number zero. Perl supports lots of different kinds of control structures which tend to be like those in C. Is $a numerically unequal to $b? Is $a string-equal to $b? Is $a string-unequal to $b? You can also use logical and. Here we discuss a few of them. reads the file denoted by the filehandle into the array @lines. and so until the end. If @food is empty to start with then the block of statements is never executed. or and not: ($a && $b) ($a || $b) !($a) # Is $a and $b true? # Is either $a or $b true? # is $a false? . and the empty string are counted as false. } # Visit each item in turn # and call it $morsel # Print the item # That was nice The actions to be performed each time are enclosed in a block of curly braces. Note that the <INFO> expression reads in the file entirely in one go. Control structures More interesting possiblities arise when we introduce control structures and looping.

Then while test is true the block of actions is executed. inc) { first_action. Second. First. It has the form for (initialise.. After each time the block is executed inc takes place. $a = <STDIN>. $a = <STDIN>. while ($a ne "fred") { print "sorry. # Start with $i = 1 # Do it while $i < 10 # Increment $i before repeating while and until Here is a program that reads some input from the keyboard and won't continue until it is the correct password #!/usr/local/bin/perl print "Password? ". Again? ". etc } First of all the statement initialise is executed. #!/usr/local/bin/perl do { "Password? ". This executes the block repeatedly until the expression is true. The while structure should be fairly clear. chop $a.for Perl has a for structure that mimics that of C. ++$i) { } print "$i\n". test. but this is the opportunity to notice several things. $i < 10. Here is an example for loop to print out the numbers 0 to 9. second_action. we can we read from the standard input (the keyboard) without opening the file first. Another useful technique is putting the while or until check at the end of the statement block rather than at the beginning. for ($i = 0. The chop function removes the last character of a string which in this case is the newline. If we forgo the sorry.. This will require the presence of the do operator to mark the beginning of the block and the test at the end. Again message in the above password program then it could be written like this. } # # # # Ask for input Get input Remove the newline at end While input is wrong. when the password is entered $a is given that value including the newline character at the end. chop $a. # Ask for input . not while it is true. To test the opposite thing we can use the until statement in just the same way. # Ask again # Get input again # Chop off newline again The curly-braced block of code is executed while the input does not equal the password.

try this has one character\n". It will also give an "empty" result if $a is the string 0. # Now. . String matching One of the most useful features of Perl (if not the most useful feature) is its powerful string manipulation facilities. At the heart of this is the regular expression (RE) which is shared by many other UNIX utilities. # If that fails. In this. try this has two characters\n". For this. } while ($a ne "fred") # Get input # Chop off newline # Redo while wrong input Conditionals Of course Perl also allows if/then/else statements.$a = <STDIN>. chop $a. remember that an empty string is considered to be false. # If above fails. it is important to notice that the elsif statement really does have an "e" missing. It is also possible to include more alternatives in a conditional statement: if (!$a) { print "The string } elsif (length($a) == 1) { print "The string } elsif (length($a) == 2) { print "The string } else { print "The string } # The ! is the not operator is empty\n". everything has failed has lots of characters\n". print "The string is empty\n". These are of the following form: if ($a) { } else { } print "The string is not empty\n".

$sentence =~ /the/ The RE is case sensitive. and matching occurs with the =~ operator. } The $_ variable is the default for many Perl operations and tends to be used very heavily.. More on REs In an RE there are plenty of special characters. The $_ special variable We could use a conditional as if ($sentence =~ /under/) { print "We're talking about rugby\n". } which would print out a message if we had either of the following $sentence = "Up and under". t..e # t followed by anthing followed by e # This will match the # tre # tle # but not te . But it's often much easier if we assign the sentence to the special variable $_ which is of course a scalar. and it is these that both give them their power and make them appear very complicated./ slashes to be used. The operator !~ is used for spotting a non-match. then the above match will be false. Remember that should be enclosed in /. In the above example $sentence !~ /the/ is true because the string the does not appear in $sentence.Regular expressions A regular expression is contained in slashes. If we do this then we can avoid using the match and non-match operators and the above can be written simply as if (/under/) { print "We're talking about rugby\n". their creation can be something of an art form. ^ $ * + ? # # # # # # Any single character except a newline The beginning of the line or string The end of the line or string Zero or more of the last character One or more of the last character Zero or one of the last character and here are some example matches. so if $sentence = "The quick brown fox". The following expression is true if the string the appears in variable $sentence. Here are some special RE characters and their meaning . $sentence = "Best winkles in Sunderland". It's best to build up your use of REs slowly.

|. newline. Square brackets are used to match any one of the characters inside them.. / and so on are peculiar cases in regular expressions. tab. The same as [0-9] Any non-digit. The same as [^a-zA-Z0-9_] Any digit. Here are some more special characters: \n \t \w \W \d \D \s \S \b \B # # # # # # # # # # # # # A newline A tab Any alphanumeric (word) character. etc Any non-whitespace character A word boundary..) can be used to group things together: jelly|cream (eg|le)gs (da)+ # Either jelly or cream # Either eggs or legs # Either da or dada or dadada or. A line with nothing in it. ). Inside square brackets a .. A vertical bar | represents an "or" and parentheses (. This is because the . The rest is mostly just for reference. If you want to match for one of those then you have to preceed it by a backslash. \. matches anything except a newline and the * means zero or more of these. [. The same as [^0-9] Any whitespace character: space. So: .^f ^ftp e$ tle$ und* . outside [] only No word boundary Clearly characters like $. There are even more options.indicates "between" and a ^ at the beginning means "not": [qjk] [^qjk] [a-z] [^a-z] [a-zA-Z] [a-z]+ # # # # # # Either q or j or k Neither q nor j nor k Anything from a to z inclusive No lower case letters Any letter Any non-zero sequence of lower case letters At this point you can probably skip to the end and do at least most of the exercise..* ^$ # # # # # # # # # # # # # # tale f at the beginning of a line ftp at the beginning of a line e at the end of a line tle at the end of a line un followed by zero or more d characters This will match un und undd unddd (etc) Any string without a newline. The same as [a-zA-Z0-9_] Any non-word character.

0" and "/0. As the previous one.00" etc and "/ 0." and "/ 0. Some example REs As was mentioned earlier.00" etc. Remember that to use them for matching they should be put in /.0" and "/ 0. Accepts "/0." and "/0. A division by zero with possibly some spaces: "/0" or "/ 0" or "/ 0" etc.. .\| \[ \) \* \^ \/ \\ # # # # # # # Vertical bar An open square bracket A closing parenthesis An asterisk A carat symbol A slash A backslash and so on. but with decimal point and maybe some 0s after it. it's probably best to build up your use of regular expressions slowly./ slashes [01] \/0 \/ 0 \/\s0 \/ *0 \/\s*0 \/\s*0\.0* # # # # # # # # # # # # # Either "0" or "1" A division by zero: "/0" A division by zero with a space: "/ 0" A division by zero with a whitespace: "/ 0" where the space may be a tab etc.. Here are a few examples. A division by zero with possibly some whitespace.

Sign up to vote on this title
UsefulNot useful