John W. Krahn wrote:
> Greg Carrara wrote:
> >
> > Hello,
>
> Hello,
>
> > I'm trying to write a script that reads a file line by line and if
> > the line contains a space it puts quotation marks around it and
> > writes it to another file. I mostly have this working except that
> > in the case of the lines that contain the space it puts the
> > quotation mark at the beginning of the next line. My guess is that
> > print OUTFILE ($line);
> > also feeds a CR. Is there a way around this?
> > thanks,
> > gc
> >
> > unless (open(INFILE, "accounts.txt")) {
> > die ("Cannot open input file accounts.txt.\n");
> > }
>
> You should include the $! variable in the error message so you know
> WHY
> it failed.
>
> open INFILE, 'accounts.txt' or die "Cannot open input file
> accounts.txt. $!\n";
>
>
> > unless (open(OUTFILE, ">nospace.txt")) {
> > die ("Cannot open output file nospace.txt.\n");
> > }
>
> open OUTFILE, '>nospace.txt' die "Cannot open output file nospace.txt.
> $!\n";
>
>
> > $line = <INFILE>;
> > while ($line ne "") {
> > if ($line =~ / +/) {
> > print OUTFILE ('"');
> > print OUTFILE ($line);
> > print OUTFILE ('"');
> > }
> > else {
> > print OUTFILE ($line);
> > }
> > $line = <INFILE>;
> > }
> > }
>
> while ( <INFILE> ) {
> s/( +)/"$1"/g;
> print OUTFILE;
> }
Your solution puts quotation marks around all contiguous strings
of spaces, while what is needed is to quote the entire line
if it contains a space. (I imagine this is a series of file paths.)
This should do the trick:
use strict;
@ARGV = qw( accounts.txt );
open STDOUT, "> nospace.txt" or die $!;
while (<>) {
chomp;
s/^|$/"/sg if / /;
print "$_\n";
}
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]