Hashes #4

#0 | #1 | #2 | #3 | #4 | #5 | #6 | #7

We've seen a good example of a hash that already exists, but now we need to know how to add new items to it or delete items.

Using our example of my music library, how do we add another artist, cd, or both?

First let's add another artist & CD:
'Aes Dana - Aftermath 2.0 (Archives of Peace)'

With our existing file, the structure is basically:

To add an artist follow the same structure:

($Andx,$Cndx) = (1,1); # initialize 2 variables at once
print "Adding 'Aes Dana' ...\n";
$music{"Aes Dana"} = ({
    "Aftermath 2.0 (Archives of Peace)" => {
        "01" => "Aftermath # 01",
        "02" => "Aftermath # 02",
        "03" => "Aftermath # 03",
        "04" => "Aftermath # 04",
        "05" => "Aftermath # 05",
        "06" => "Aftermath # 06",
        "07" => "Aftermath # 07",
        "08" => "Aftermath # 08",
        },
    },
);

And to print our music collection ...

foreach $artist (sort keys (%music)) {
    print "$Andx $artist\n"; 
    $Andx++;
    $Cndx=1; # initialize for each artist
    foreach $cd (sort keys $music{$artist}) {
        print "\t $Cndx $cd\n"; 
        $Cndx++;
        foreach $tracknum (sort keys $music{$artist}{$cd}) {
            print "\t\t$tracknum $music{$artist}{$cd}{$tracknum}\n";
       }
    }
}

I think we should add another just to be safe!

print "Adding 'Acoustic Alchemy' ...\n";
$music{"Acoustic Alchemy"} = ({
            "Back on the Case" => {
                "01"=>"The Alchemist",
                "02"=>"Jamaica Heartbeat",
                "03"=>"Georgia Peach",
                "04"=>"Playing for Time",
                "05"=>"When the Lights Go Out",
                "06"=>"Clear Air for Miles",
                "07"=>"Fire of the Heart",
                "08"=>"Freeze Frame",
                "09"=>"On the Case",
                "10"=>"Break for the Border",
                },
            },
);

The same code prints our collection again ...

foreach $artist (sort keys (%music)) {
    print "$Andx $artist\n"; 
    $Andx++;
    $Cndx=1; # initialize for each artist
    foreach $cd (sort keys $music{$artist}) {
        print "\t $Cndx $cd\n"; 
        $Cndx++;
        foreach $tracknum (sort keys $music{$artist}{$cd}) {
            print "\t\t$tracknum $music{$artist}{$cd}{$tracknum}\n";
       }
    }
}

Now I think we understand how this works.

But of course, sometimes we lose a CD or give it to someone ...