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!

Recommended Answers

All 2 Replies

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]";

$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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.