Angle brackets - the line input and globbing operators

You will have encountered the line input operator <> before, in situations such as these:

# reading lines from STDIN
while (<>) {
        ...
        ...
}

# reading a single line of user input from STDIN
my $input = <STDIN>

The line input operator is discussed in-depth on page 53 of the Camel. Read it now.

The globbing operator is nearly, but not quite, identical to the line input operator. It looks the same, and it acts partly in a similar way, but it really is a separate operator.

The filename globbing operator is documented on page 55 of the Camel.

If the angle brackets have anything in them other than a filehandle or nothing, it will work as a globbing operator and whatever is between the angle brackets will be treated as a filename wildcard. For instance:

my @files = <*.txt>

The filename glob *.txt is matched against files in the current directory, then either they are returned as a list (in list context, as above) or one scalar at a time (in scalar context).

If you get a list of files this way, you can then open them in turn and read from them.

while (<*.txt>) {
        open (FILEHANDLE, $_) || die ("Can't open $_: $!");
        ...
        ...
        close FILEHANDLE;
}

The glob() function behaves in a very similar manner to the angle bracket globbing operator.

my @files = glob("*.txt")

foreach (glob "*.txt") {
        ...
}

The glob() is considered much cleaner and better to use than the angle-brackets globbing operator.

Exercises

  1. Use the line input operator to accept input from the user then print it out

  2. Modify your previous script to use a while loop to get user input repeatedly, until they type "Q" (or "q" - check out the lc() and uc() functions in chapter 3 of your Camel book) (Answer: exercises/answers/userinput.pl)

  3. Use the file globbing function or operator to find all Perl scripts in your home directory and print out their names (assuming they are named in the form *.pl) (Answer: exercises/answers/findscripts.pl)

Advanced exercises

  1. Use the above example of globbing to print out all the Perl scripts one after the other. You will need to use the open() function to read from each file in turn. (Answer: exercises/answers/printscripts.pl)