0

Hi!

I split lines on tabs (fields). I would like Perl to print first filed in parenthesis.
My script is the following:

open (INP, "input.txt") or die "Can't open input: $!\n";
open (OUT, ">>output.txt") or die "Can't open output: $!\n";
while ($line = <INP>) {
chomp ($line);
@field = split (/\s+/, $line);
$name = "$field[0]\t$field[1]";
print OUT "$name\n";
}
close INP;
close OUT;

e.g. for a line in input file
1 22 45
2 23 89
I would like to have output looking like:
(1) 22
(2) 23

Big thanks for help!

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by KevinADC
0

Hmmm. I think you're going to hate one of us two. :) Putting parens around the field name as shown below should do the trick...

$name = "($field[0])\t$field[1]";

0

$name is being used for no good reason that I can see:

open (INP, "input.txt") or die "Can't open input: $!\n";
open (OUT, ">>output.txt") or die "Can't open output: $!\n";
while ($line = <INP>) {
   chomp ($line);
   @field = split (/\s+/, $line);
   print OUT "($field[0])\t$field[1]\n";
}
close INP;
close OUT;

No need to make a new string just to print to the file. I added \n to the end of the line, remove it if you don't want a newline on the end.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.