Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^3: Creating a Multi Level Hash from CSV

by AnomalousMonk (Bishop)
on May 13, 2021 at 20:02 UTC ( #11132550=note: print w/replies, xml ) Need Help??


in reply to Re^2: Creating a Multi Level Hash from CSV
in thread Creating a Multi Level Hash from CSV

... explain the sub chain{} function ...

The"Perl Magick" here is recursion; it is not peculiar to Perl in any way.

sub chain { return @_ > 1 ? { shift() => chain(@_) } : shift(); }
If there are two or more items in the @_ function argument array (@_ > 1), { shift() => chain(@_) } executes. shift takes the top argument off of @_ and makes it a hash key with the value of whatever the call to chain(@_) returns. Note that chain(@_) is called with whatever remains in the @_ array after one item has been removed by the shift call. This key/value pair is then returned within an anonymous hash reference.

If there are fewer than two items in the @_ array, the call to chain(@_) simply returns the top item in the array. Note that this does not "properly" handle the case in which the @_ array is empty. What is "proper" handling in this case (if it can even arise)? Only you can figure this out.

Win8 Strawberry 5.8.9.5 (32) Thu 05/13/2021 15:26:20 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings my %hash; # my ( $top, @rest ) = split /,|\n/; # FIXME faking CSV for testing my ($top, @rest) = qw(foo); $hash{$top} = chain(@rest); use Data::Dump 'dd'; dd \%hash; sub chain { return @_ > 1 ? { shift() => chain(@_) } : shift(); } ^Z { foo => undef }

... remove the first row so the header doesn't do what the rest of the hash is doing.

One might do the following:
    open(my $input, '<:utf8',"input.csv") or die;

    <$input>;  # read and discard one line/record
(I think Text::CSV can do this for you (it does just about everything else :), but you'll have to check for yourself.)


Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2021-10-17 04:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (71 votes). Check out past polls.

    Notices?