Tigor:

You were pretty close with your code. The problem is how you built your key.

In your desired output, you show that you want to use the first column as the key, but you used:

my $key = join(' ', splice(@fields, 0, 2)); \_______ ____________/ \ v \ (1) \___ __________________________/ v (2)

That explicitly (1) takes the first two columns out of @fields (two columns starting at zero), and then (2) joins them together with a space to build $key.

Since you wanted only the first column as the key, you could have used:

my $key = splice(@fields, 0, 1);

which would have taken just the first column and used it as the key. However, there are other ways. The shift operator, for example, will remove the first item from a list, so you could get the same result like this:

my $key = shift @fields;

However the method I would use is the same one proposed by poj, which is to do it when you split the line into fields:

my ($key, @fields) = split;

Here, when split creates a list of values, it puts the first one in $key and the rest of them in @fields. Note: when you do it like this, the first array on the left side will consume *all* the values. So doing something like the following:

my ($key,@first_quarter, $apr) = split;

leaves the last value undefined. You'd get $key='Apple', @fields=[40, 45, 50, 54], and $apr=undef for the first line of data.

Update: I bumbled Tigor's name. Thanks, chirooba! ;^)

...roboticus

When your only tool is a hammer, all problems look like your thumb.


In reply to Re: Adding text file data to hashes and array by roboticus
in thread Adding text file data to hashes and array by Tigor

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.