On 01/12/2011 14:43, Melvin wrote:
Hi I have a file in the following format
111
222
333
Now I need to print the following output from the given input file as
111 222 333
Is there a way I can do this in perl?
I tried 2 ways (both ere essentially the same)
1) Parsing the file and pushing the inputs to a string array. However
since the inputs had a newline, I could n't remove them
2) Using the .="" operator to concatenate. Here too, the newlines from
the file were taken.
my $parent_loop;
my $line_cnt;
my @lines;
my @output;
You should declare your variables as closely as possible to the point
of first-use.
open (FILE_PATTERN ,$ARGV[0]) || die ("ERROR: NO INPUT, NO OUTPUT
hahaha");
It is best to use lexical file handles and the three-parameter form of
open. Also include the $! variable in the die string so that you can see
/why/ the open failed.
open my $file_pattern, '<', $ARGV[0] or die "ERROR: $!";
while (<FILE_PATTERN>) {
push @lines, $_;
$line_cnt++;
}
That loop is the same as
my @lines = <$file_pattern>;
my $line_cnt = @lines;
(but you don't neede $line_cnt)
close (FILE_AUDIO);
for ($parent_loop=0; $parent_loop< $line_cnt; $parent_loop++) {
push @output,"$lines[$parent_loop]";
}
You shouldn't put scalar variables in double-quotes unless you know
what that does.
That loop is the same as
my @output = @lines;
for ($parent_loop=0; $parent_loop<= $line_cnt; $parent_loop++) {
print $urg_command[$parent_loop];
}
There is nothing in @urg_command!
My suggestion for a solution is below.
HTH,
Rob
use strict;
use warnings;
open my $file_pattern, '<', $ARGV[0] or die "ERROR: $!";
my @lines = <$file_pattern>;
chomp @lines;
print "@lines\n";
**OUTPUT**
111 222 333
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/