Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Adding Filename to the end of each line

by haukex (Archbishop)
on Apr 09, 2021 at 19:45 UTC ( [id://11131071]=note: print w/replies, xml ) Need Help??


in reply to Adding Filename to the end of each line

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; }

Replies are listed 'Best First'.
Re^2: Adding Filename to the end of each line
by jalopez453 (Acolyte) on Apr 09, 2021 at 20:57 UTC

    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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11131071]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-23 11:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found