in reply to print datafields separated by tab

Your data has newline characters at the end of each element. For example, you think you are looking at...

ABCD EFGH GHIJ

But what you've really got in your array is:

ABCD\n EFGH\n GHIJ\n

The first print statement prints one element, with a newline. The second statement prints a single tab on the new line. On the next iteration, the next field is printed on that same new line, and another newline is output. Then another tab, from the next new line, and so on. So you're always starting over with a new line, and always tabbing from the beginning of that new line.

You should be chomping the data. If you don't really care or need for it to have newline characters in it, chomp them as the data is slurped into the array.

Try this:

my @array; while ( my $line = <STDIN> ) { chomp $line; push @array, $line; } #.... later on... foreach ( @array ) { print "$_\t"; }

A slightly more obfuscated way of printing the list, while avoiding using a foreach (or for) loop could be:

{ local $, = "\t"; print @array, "\n"; }

The preceeding example sets the output field separator, contained in $, to the tab character. Just don't forget to switch it back or you'll have a mess in other places in the program.

Hope this helps...

UPDATE: Egads, too early in the morning. Code has been fixed. Thanks for the head's up. Duh!

Dave

"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: print datafields separated by tab
by thinker (Parson) on Aug 23, 2003 at 16:52 UTC

    Hi davido,

    This is wrong in (at least) 2 regards. Firstly, the syntax is wrong in the while loop. What you needed was

    while (my $line = <STDIN> ) {

    Secondly, chomp does not return what you think it does. It returns the number of characters it removes, in your case 1 for each iteration. So your final result will be like

    1    1    1

    Hope this helps

    thinker

      Wiping sleepy sand out of eyes..... Thanks for the head's up. I've fixed what should have been simple code. That will teach me to cut the 'test it first' corner. ;)

      By the way, you can see my use of chomp's seldom-used return value here: Chomped JAPH.

      Thanks again.

      Dave

      "If I had my life to do over again, I'd be a plumber." -- Albert Einstein