Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Adding text file data to hashes and array

by roboticus (Chancellor)
on Feb 13, 2019 at 16:10 UTC ( [id://1229878]=note: print w/replies, xml ) Need Help??


in reply to Adding text file data to hashes and array

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1229878]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-04-25 10:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found