R
rzaleski
How can I swap two columns in a file with perl?
How can I swap two columns in a file with perl?
I'm not %100 positive on this but:How can I swap two columns in a file with perl?
How can I swap two columns in a file with perl?
How can I swap two columns in a file with perl?
jpeg said:How can I swap two columns in a file with perl?
split and array slices work well. Here's an example for a tab-delimited
file.
#!/usr/bin/perl
use strict;
my @cols;
while (<DATA>) {
chomp;
@cols = split(/\t/, $_);
print ($cols[1] . "\t" . $cols[0] . "\n");
}
__DATA__
1 2
3 4
5 6
7 8
9 10
Josef Moellers said:jpeg said:How can I swap two columns in a file with perl?
split and array slices work well. Here's an example for a tab-delimited
file.
#!/usr/bin/perl
use strict;
my @cols;
while (<DATA>) {
chomp;
@cols = split(/\t/, $_);
print ($cols[1] . "\t" . $cols[0] . "\n");
}
__DATA__
1 2
3 4
5 6
7 8
9 10
This only works if there is only a single tab in the file.
In general, however, this works if you change the print to the following:
{ my $tmp = $cols[1]; $cols[1] = $cols[0]; $cols[0] = $tmp; }
print join("\t", @cols), "\n";
Most likely, there is some clever way to replace the first line by a
single statement or do without $tmp ...
Anno said:Josef Moellers said:jpeg said:On Thu, 06 Apr 2006 17:27:48 -0700, rzaleski wrote:
How can I swap two columns in a file with perl?
split and array slices work well. Here's an example for a tab-delimited
file.
#!/usr/bin/perl
use strict;
my @cols;
while (<DATA>) {
chomp;
@cols = split(/\t/, $_);
print ($cols[1] . "\t" . $cols[0] . "\n");
}
__DATA__
1 2
3 4
5 6
7 8
9 10
This only works if there is only a single tab in the file.
In general, however, this works if you change the print to the following:
{ my $tmp = $cols[1]; $cols[1] = $cols[0]; $cols[0] = $tmp; }
print join("\t", @cols), "\n";
Most likely, there is some clever way to replace the first line by a
single statement or do without $tmp ...
Certainly:
@cols[ 0, 1] = @cols[ 1, 0];
print join("\t", @cols), "\n";
How can I swap two columns in a file with perl?
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.