http://qs321.pair.com?node_id=1125666

sumathigokul has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, i want to search in a text file for '2' and copy the whole statement in another text file. Here is the code. It prints those matched statements and it also generated new.txt file, but the file is empty.

use strict; my $find = "2"; open (FILE, "<high_fanout.txt") or die "could not open:$!"; my @line = <FILE>; for (@line) { if ($_ =~ /$find/) { print "$_\n"; print NEW "@line\n"; } } open (NEW, ">new.txt" ) or die "could not open:$!"; close (FILE); close (NEW);

can anyone help me out from this mistake? Thank you all.

  • Comment on Perl script to find particular string and save those lines in another file?
  • Download Code

Replies are listed 'Best First'.
Re: Perl script to find particular string and save those lines in another file?
by graff (Chancellor) on May 05, 2015 at 05:24 UTC
    You seem to be opening the "NEW" file handle after you've been trying to write to it. Trying opening "NEW" before the "for" loop.

    (Also, it's better to do it like this:

    use strict; my $find = "2"; open( NEW, ">", "new.txt" ) or die "..." open( FILE, "<", "high_fanout.txt") or die "..." while (<FILE>) { print NEW if ( /$find/ ); }
    (updated to "use strict" and add "my" for the one variable)

      Thank you, this code works.

      use strict; my $find = "2"; open (NEW, ">", "new.txt" ) or die "could not open:$!"; open (FILE, "<", "high_fanout.txt") or die "could not open:$!"; while (<FILE>) { print NEW if (/$find/); } close (FILE); close (NEW);
Re: Perl script to find particular string and save those lines in another file?
by aaron_baugher (Curate) on May 05, 2015 at 05:39 UTC

    You need to open the output file before you write to it. Move the "open (NEW" line up above the loop that prints to it.

    Aaron B.
    Available for small or large Perl jobs and *nix system administration; see my home node.

Re: Perl script to find particular string and save those lines in another file?
by hdb (Monsignor) on May 05, 2015 at 05:25 UTC

    You have to open your NEW file before you print into it.