### Re^2: Replacing values in an array

by tonto (Friar)
 on Jan 26, 2013 at 23:43 UTC ( #1015547=note: print w/replies, xml ) Need Help??

in reply to Re: Replacing values in an array
in thread Replacing values in an array

Seeing the same solution written differently makes it more clear to me, I am very grateful to you. I will study hashes until I get them through my thick skull! I have spent days on this.
Again, my sincere thanks!
-tonto

Replies are listed 'Best First'.
Re^3: Replacing values in an array
by muba (Priest) on Jan 27, 2013 at 05:17 UTC

You can consider a hash to be much like an array, except instead of numerical indexes to access individual elements, you use strings as keys.

```# Define an array:
my @basket = qw(apple banana cherry);

# Get an element from the array:
# (remember that indexes are 0-based)

# Change an element:

The above example shouldn't be unfamiliar. Now, instead of keeping a @basket that tells us what kinds of fruit we have in the basket, let's keep a %basket that can also tell us how much of that kind of fruit we have.

```# Define the hash:
apple    => 12,
banana   =>  6,
cherry  =>  32,   # This final comma is optional,
);                    # but makes it easier to add more lines in the f
+uture.

# Get an element from the basket:

# Modify elements:

# Get all keys in the hash:
print "Fruits in my basket: ", join(", ", sort keys %basket), "\n";

# Using a variable as a key:
for my \$fruit (sort keys %basket) {
+n";
}

# The 'each' function:
while (my (\$fruit, \$amount) = each %basket) {
print "There are \$amount \${fruit}s in my basket.\n";
}

# Getting rid of an element:
print "Fruits in my basket: ", join(", ", sort keys %basket), "\n";

That pretty much covers the basics of hashes. Nothing to be afraid of, and quite a useful data type!

Create A New User
Node Status?
node history
Node Type: note [id://1015547]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2018-03-18 16:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When I think of a mole I think of:

Results (230 votes). Check out past polls.

Notices?