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

I am trying to add the filename to the end of each line in my files. I tried a few solutions but none seem to work and this is what I have. I am not sure what I am missing or what is wrong.

#!/usr/bin/perl -w use strict; use warnings; use Text::ParseWords; opendir IN, 'Master'; my @in = grep { /\.txt$/ } readdir IN; # read all file names form dir +except names started with dot closedir IN; for my $in (@in) { open IN, '<', "Master/$in" || next; open OUT, '>', "Update/$in" || die "can't open file Update/$in"; my @file = @in while (my $file = <IN>) { my $line = $_; $updateline = $line . $file; print OUT "$updateline"; } close OUT; close IN; }

Replies are listed 'Best First'.
Re: Adding Filename to the end of each line
by haukex (Archbishop) on Apr 09, 2021 at 19:45 UTC

    Note that your code does not compile: you're missing a semicolon on the line my @file = @in (and I don't think that line is necessary in the first place, since @file never gets used), and you haven't declared $updateline. And a few comments on other parts of the code: your two open statements are incorrect in that the || operator is not the right thing to use here, see "open" Best Practices for why. Also, your comment "read all file names form dir except names started with dot" doesn't actually describe what the code is doing, so it's confusing, and you should check your opendir for errors as well. And I final nit: you don't need warnings and the -w on the shebang, drop the latter.

    In regards to the actual issue: You're reading lines from the IN filehandle into the $file variable. Because of this, $_ does not contain the current line. Your outer for loop is putting each filename in $in, not $file. Also, note that lines read from the input file will still contain the newline character at the end, so you probably should chomp that so that appending something to the line works properly. Taking all that together, changing some variable names, and indenting your code properly:

    #!/usr/bin/perl use warnings; use strict; opendir my $dh, 'Master' or die "opendir: $!"; my @files = grep { /\.txt$/ } readdir $dh; closedir $dh; for my $file (@files) { open my $ifh, '<', "Master/$file" or next; open my $ofh, '>', "Update/$file" or die "can't open file Update/$ +file: $!"; while ( my $line = <$ifh> ) { chomp($line); my $updateline = $line . $file; print $ofh $updateline, "\n"; } close $ofh; close $ifh; }

      Sorry about that, I noticed that I copied and pasted the wrong code I was working on, but somehow you were still able to understand what I was trying to do. I see now where my mistake was, it was pretty much spot on to what you posted, where I went wrong was the print function, I had it as print $ofh $updateline; and that was it. the missing piece was the comma and "\n" .. thank you again for helping me.