User Tools

Site Tools


tutorials:perl_exercises

This is an old revision of the document!


Perl Exercises

read_and_write

Read from an input file and write the content to an output file. Assume the two filenames are provided in the command line.

Hint: you need to know about filehandle before attempting this exercise.

$ cat input.txt 
George Washington
John Adams
Thomas Jefferson
James Madison
James Monroe
$ perl read_and_write.pl input.txt output.txt
$ cat output.txt 
George Washington
John Adams
Thomas Jefferson
James Madison
James Monroe

See a sample answer here

count_first_name

Read an input file that contains several names (assuming one name in each line, the first name and the last name are separate by a space). Count how the number of times each first name appeared in the input. Print the result to STDOUT, sort the names alphabetically.

Hint: you need to know about filehandle, array, hash, and sorting before attempting this exercise.

$ cat input.txt 
George Washington
John Adams
Thomas Jefferson
James Madison
James Monroe
$ perl count_first_name.pl input.txt 
George appeared 1 times
James appeared 2 times
John appeared 1 times
Thomas appeared 1 times

See a sample answer here

tutorials/perl_exercises.1280588505.txt.gz · Last modified: by chkuo