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


In reply to Re: print datafields separated by tab by davido
in thread print datafields separated by tab by bandya

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.