Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble deleting key and it's associated value from a perl hash

Tags:

arrays

hash

perl

I'm writing a basic song managment program in perl that via the use of a module allows the user to add a song name and song time pair to a hash where the key is the name of the song and the value is the time of the song, both of them are strings. The addSong is functioning perfectly however the removeSong is not. In the removeSong I first want to check if the song name string passed in exists as a key. If the input matches an existing key it is deleted(along with it's corresponding value) and if it isn't the subroutine gives out an error message. When I proceed to test the subroutine by removing the song "Hello" I receive the error message I programed in that is given out when the input doesn't match a key and when I use the Data::Dumper function on the hash I can see that the song key I wanted to remove is still in the hash.

I used this stackoverflow link for help: How to remove keys from hash in Perl?

Here is the code for my test.pl function:

use warnings;
use FindBin;
use lib $FindBin::Bin;
use SongList;
use strict;

SongList::addSong("Hello", "5.23");
SongList::addSong("all my heros are cornballs", "3:23");
SongList::addSong("Grimy Waifu", "2:55");
SongList::addSong("ptsd", "2:28");
SongList::removeSong("Hello");

And here is the code for my SongList.pm module:

package SongList;
#DECLARE VARIABLES AS LOCALLY AS POSSIBLE TO PREVENT BUGS
use strict;
use warnings;
use Data::Dumper;
my %songhash;

my $songlisttitle;
sub addSong{#this works


    my ($namesong, $timesong) = @_;
    $songhash{$namesong}=$timesong;
    print "success\n";
    print Dumper(\%songhash);

}

sub removeSong{
    my $namesong=@_;

    print "removing song from list\n";
    if(exists $songhash{$namesong}){
    delete($songhash{$namesong})
    }
else{
    print "that song wasn't in the list anyways\n";
    }
    print Dumper(\%songhash);
}
like image 653
kikikey Avatar asked Mar 03 '23 07:03

kikikey


1 Answers

Here:

sub removeSong{
    my $namesong=@_;

You are assigning an array to a scalar variable. This results in the length of the array being assigned to the scalar (this will be 1 if a single argument was passed as expected). Since key 1 does not exists in the hash, you get the error message.

You want:

my ($namesong) = @_;

Or:

my $namesong = shift;

Reference: perldata:

If you evaluate an array in scalar context, it returns the length of the array.

like image 148
GMB Avatar answered May 07 '23 04:05

GMB