sliddy
sliddy

Reputation: 135

Can't write to the file

Why can't I write output to the input file?

It prints it well, but isn't writing to the file.

my $i;
my $regex = $ARGV[0];

for (@ARGV[1 .. $#ARGV]){
    open (my $fh, "<", "$_") or die ("Can't open the file[$_] ");
    $i++;
    foreach (<$fh>){
        open (my $file, '>>', '/results.txt') or die ("Can't open the file "); #input file
        for (<$file>){
            print "Given regexp: $regex\nfile$i:\n   line $.: $1\n" if $_ =~ /\b($regex)\b/;
        }
    }
}

Upvotes: 1

Views: 245

Answers (1)

Borodin
Borodin

Reputation: 126762

It's unclear whether your problem has been solved.

My best guess is that you want your program to search for the regex passed as the first parameter in the files named in the following paramaters, appending the results to results.txt.

If that is right, then this is closer to what you need

use strict;
use warnings;
use autodie;

my $i;
my $regex = shift;

open my $out, '>>', 'results.txt';

for my $filename (@ARGV) {
  open my $fh, '<', $filename;
  ++$i;
  while (<$fh>) {
    next unless /\b($regex)\b/;
    print $out "Given regexp: $regex\n";
    print $out "file$i:\n";
    print $out "line $.: $1\n";
    last;
  }
}

Upvotes: 4

Related Questions