"be consistent" | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
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:
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
|
|