Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

tabs to spaces

Status
Not open for further replies.

yankees26

Programmer
Aug 5, 2006
7
US
I'm trying to write a program that turns tabs into spaces but it doesn't work.
Code:
#!/usr/bin/perl

$argc = 0;

foreach (@ARGV)

{

    ++$argc;

}



if ($argc ne 1)

{

    die "You either have none or not enough arguments.\n"

}

my $tab = "\t";

my $spaces = "    ";

open FILE, $ARGV[1];

@LINES = <FILE>;

close FILE;

foreach $lines (@LINES)

{

    $lines =~ s/$tab/$spaces/gx;

}

print @LINES;
 
The regular expression doesn't do variable interpolation properly of whitespace characters. Hard code the regex instead.

$lines =~ s/\t/ /gx;
 
You have to open a filehandle for writing out, otherwise you are just printing to the screen.

open OUT, "$new_file";
...
print OUT @LINES;
 
Some other problems with your code.

If you are only passing one file name from the command line, then you need to call $ARGV[0] not $ARGV[1]. You should also use strict and add error checking to your file reads and file writes. It will go a long way to helping troubleshoot problems. Here is some cleaned up code.

Code:
use strict;
die "Not enough arguments." unless @ARGV == 1; # condense error check

open FILE, "$ARGV[0]" || die "$!"; # add error check
my @lines = <FILE>;
close FILE;
open OUT, ">$ARGV[0]" || die "$!"; # add error check

foreach my $lines (@lines) { 
    $lines =~ s/\t/    /gx; # replace tab with space
}

print OUT @lines;
close (OUT);
 
Well, I wanted it to print to the screen. Thanks for the help (not really sure why I had @ARGV[1]).

Although, I still have two questions. || can be replaced with or, correct? And what does my do?
 
Also, forget to ask something. I know the g at the end of regular expression makes it global, but I can't remember what the x does?
 
x means ignore whitespace!
It's a tool for commenting regex's.
|| can generally be replaced with "or" but be careful because they do have different operator precedences.
"my" creates a scoped variable. One that only exists (generally) for the block that it was defined in.


Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top