Jabox has asked for the wisdom of the Perl Monks concerning the following question:

Good day Everyone!

I need help again, the problem was similar to Push,pop, and splice!

This time I wanted to make it work with a "storage.txt" file and a "inventory.txt" file.

My practice is a mess again :D

open (FILE, ">>Storage.txt") or die "Can not open file\n"; flock(FILE,2); my %sfi = <FILE>; print "Would you like to add or delete items for the Storage?\ +n"; print "1. Add\n", "2. Delete\n", "3. Back\n", "4. List\n", "5. Cancel\n"; my $choice = lc(<STDIN>); chomp $choice; if (($choice eq "add") || ($choice eq 1)) { print "What items would you like to add?\n"; my $ans = lc(<STDIN>); chomp $ans; print FILE "$ans\n"; print "The storage contains the following\n"; foreach my $sfi (%sfi) { print "$sfi\n"; } &stor; } elsif (($choice eq "delete") || ($choice eq 2)) { print "What items would you like to delete?\n"; my $ans = lc (<STDIN>); chomp $ans; my @find = grep {$_ =~ $ans} %sfi; if (exists %sfi {my $find = @find?? << not sure how to + do this part too}) { delete {$ans}; print "The storage contains the following\n"; foreach my $sfi (%sfi) { print "$sfi\n"; } &stor; }

I got a feeling someone might already face palm as soon as you see this but what I'm trying to do was to remove any words that contains any of the STDIN for the delete section.

I am also unsure if that was how I set a file to equals a hash so it can do what I was trying to do up there :)

Thank you all in advance! And the post I linked really helped my last practice :D

Replies are listed 'Best First'.
Re: Deleting a word in a file!
by davido (Cardinal) on Mar 24, 2014 at 22:25 UTC

    There are very few situations where you would want to treat hash keys the same as hash values, which is what you are doing when you grep { ... } %hash, or foreach ( %hash ) { ... }. That's probably bug as a consequence of not understanding how to use Perl's hashes. It often does make sense to iterate over a hash's keys (generate a list of them using keys), or a hash's values (values). Likewise, my( %hash ) = <INFILE> is almost certainly a bug too, unless your input file looks like this:

    some key some value some key some value

    ...which is unlikely in general, and definitely not the case for your data sets.

    I'm going to assume that you're required, for some reason, to use newline delimited flat files for your inventory list, and your storage list. Though it's probably not the most time-efficient approach, I would probably just use Tie::File, and be done with it.


    Dave

Re: Deleting a word in a file!
by toolic (Bishop) on Mar 24, 2014 at 17:07 UTC
    The following usages of a hash look strange:
    my %sfi = <FILE>; foreach my $sfi (%sfi) {

    Do you really want an array?