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

Introducing spaces between the values in a hash of hashes

by Anonymous Monk
on Jan 24, 2014 at 20:59 UTC ( #1071998=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks.

A simple question if I may? Is there an aesthetically pleasing way to display the values in a hash of hashes with spaces between the values themselves? In other words between the values of 'biology', 'math', 'history', 'full', 'open', and 'open' in the code below.

#!/usr/bin/perl use strict; use warnings; use Storable; my %h2; my %hash = ( 'roster' => { 'mike' => 'biology', 'carol' => 'math', 'tom' => 'history', }, 'courses' => { 'math' => 'full', 'biology' => 'open', 'art' => 'open', } ); store(\%hash, "test.dat"); %h2 = %{retrieve "test.dat"}; for (sort keys %h2) { print $_, " ", %{$h2{$_}}; }


Thanks.
A monkette.

Comment on Introducing spaces between the values in a hash of hashes
Download Code
Re: Introducing spaces between the values in a hash of hashes
by Kenosis (Priest) on Jan 24, 2014 at 21:17 UTC

    It's not too pretty, but you can use the baby-cart:

    use strict; use warnings; use Storable; my %h2; my %hash = ( 'roster' => { 'mike' => 'biology', 'carol' => 'math', 'tom' => 'history', }, 'courses' => { 'math' => 'full', 'biology' => 'open', 'art' => 'open', } ); store( \%hash, "test.dat" ); %h2 = %{ retrieve "test.dat" }; for ( sort keys %h2 ) { print "$_: @{[values %{$h2{$_}}]}\n"; }

    Output:

    courses: open full open roster: history math biology

    Hope this helps!

Re: Introducing spaces between the values in a hash of hashes
by kennethk (Monsignor) on Jan 24, 2014 at 21:46 UTC
    Why not just join?
    for (sort keys %h2) { print join " ", $_, values %{$h2{$_}}; }

    If you provide a (<code> tag delimited) copy of exactly what you'd like, we might be able to come up with a better answer.

    Also, if you are relying on a special variable to format properly, you should get in the habit of explicitly localizing and initializing it to the value you want. Otherwise, spooky action at a distance may come to visit.


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1071998]
Approved by davido
Front-paged by starX
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (16)
As of 2014-07-28 14:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (200 votes), past polls