Hi everyone. I have a question with regards to a Perl program that I have written for Exercise 2.1 of the book Learn Perl the Hard Way. The question goes like:
Write a program called grep.pl that takes a pattern and a list of files as command line arguments, and that traverses each file printing lines that match the pattern.
I have 4 files of which their contents are listed below: file_list.txt --> contains a list of files: "a.txt", "b.txt", "c.txt" a.txt --> Contains the word "I" b.txt --> Contains the words "am going to" c.txt --> Contains the word "school"
I have tried to write the program below, but I don't understand why it only prints the contents from a.txt, i.e. it only prints the word "I". I inserted print functions along the way and I realized that the subroutine "open_file" is called only once but I don't understand why this happens.
May I ask if anyone can give a hint on resolving this?
Thank you!
#!/usr/bin/perl use strict; use warnings; sub open_file { my $file = scalar(@_); foreach my $temp (@_) { open FILE, $temp; while (my $line = <FILE>) { print $line; } } } sub grep_file { my $file = shift; open FILE, $file; while (my $line = <FILE>) { open_file ($line); } } grep_file @ARGV
In reply to Question on File Handler and Subroutines in Perl by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |