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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.