in reply to Remove line break, then remove spaces (resolved)
To be honest, I think the logic in the code you've posted is whacked. You put close xFILE inside your foreach $line loop, as if the input file needs to be closed more than once (it doesn't), and then you open the output file inside that same foreach loop, as if you need to open an output file once for each line of text (you don't). Also, your ragged use of indentation makes it hard to figure out what's going on, and I really don't see how your code doing what you say it's supposed to be doing. And I don't understand your comment about needing to do two passes (you don't).
Anyway, here's how I would approach the problem as originally stated (if I understood that correctly): for each file containing a line that matches a specific pattern, remove the trailing whitespace from that line so that the next line becomes appended to it. Actually, the version below is a little different from what I put in the other thread: it checks the line being appended, and removes any initial whitespace.
In terms of coding style and organization, note how the "if ... elsif ... else ..." conditions are ordered so that the simple "no-op" and simple failure cases are dealt/dispensed with first; the more complicated business is handled last; in general, a loop that handles the contents of a file does not need to include opening and closing operations on files (there are only a few very rare situations where this is not true).sub Wanted { if ( !/\S\.html?$/i ) { warn "$root$File::Find::name skipped\n"; } elsif ( !open( IN, "<", $_ )) { warn "open for read failed on $root$File::Find::name : $!\n"; } else { my @lines = (); my $line; my altered = 0; while ( defined( $line = <IN> )) { if ( $line =~ /<meta\s+name="revision"\s+content=\s*$/i ) +{ $line =~ s/\s*$//; my $append = <IN>; $append =~ s/^\s+//; $line .= $append; $altered++; } push @lines, $line; } close IN; if ( $altered ) { open( OUT, ">", $_ ) or die "open for write failed on $root$File::Find::name : + $!\n"; print OUT @lines; ## NB: no need for quotes here close OUT; } warn "$root$File::Find::name finished with $altered changes\n" +; } }
It's really a matter of organizing your ideas for what the script is supposed to do, so that the sequence of steps for the program will make sense when expressed in plain English (or whatever your native human language may be). Then, the perl code should be a direct reflection of that sequence. That's a large part of what makes perl such a nice programming language.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Remove line break, then remove spaces (resolved)
by djbryson (Beadle) on Jan 22, 2007 at 18:12 UTC |