Difference between revisions of "Perl/Basics/Variables and Data Types/Hashes"
AlizaLorenzo (Talk | contribs) (Created page with "A hash is very similar to a struct in C. ====Introduction==== Hashes are prefixed by the '''%''' character. Hash element values are prefixed by '''$'''. A hash element may ...") |
Chantal21I (Talk | contribs) |
||
(One intermediate revision by one other user not shown) | |||
Line 1: | Line 1: | ||
A hash is very similar to a struct in [[C]]. | A hash is very similar to a struct in [[C]]. | ||
+ | |||
====Introduction==== | ====Introduction==== | ||
Hashes are prefixed by the '''%''' character. Hash element values are prefixed by '''$'''. A hash element may contain another hash, an array, or a scalar. | Hashes are prefixed by the '''%''' character. Hash element values are prefixed by '''$'''. A hash element may contain another hash, an array, or a scalar. | ||
Line 15: | Line 16: | ||
print "The user " . $user{'username'} . " is connected to " . $user{'network'} . "\n"; | print "The user " . $user{'username'} . " is connected to " . $user{'network'} . "\n"; | ||
</syntaxhighlight>}} | </syntaxhighlight>}} | ||
+ | |||
+ | ====Helper Functions==== | ||
+ | {{:Perl/Basics/Hashes/Helper_Functions}} |
Latest revision as of 01:54, 19 July 2012
A hash is very similar to a struct in C.
Introduction
Hashes are prefixed by the % character. Hash element values are prefixed by $. A hash element may contain another hash, an array, or a scalar.
- You can directly modify the key inside of a hash
<syntaxhighlight lang="perl">$hash{'key'} = 'value';</syntaxhighlight> |
- You can also create a key => value pair on declaration
<syntaxhighlight lang="perl">my %hash = ('key' => 'value', 'key2' => 'value2');</syntaxhighlight> |
- Example:
<syntaxhighlight lang="perl">my %user; $user{'username'} = "hatter"; $user{'network'} = "irc.blackhatacademy.org"; print "The user " . $user{'username'} . " is connected to " . $user{'network'} . "\n"; </syntaxhighlight> |
Helper Functions
each()
"while my each" can be used to isolate $key => $value pairs from a hash as follows with our %user hash:
<syntaxhighlight lang="perl">while(my($key,$value) = each(%user)) { print "Key: $key, Value: $value\n"; };</syntaxhighlight> |
keys
This uses a foreach() loop and casting. We can isolate $key=>$value pairs the same as above using keys in stead of each:
<syntaxhighlight lang="perl">foreach my $key (@{sort keys %user}) { print "Key: $key, Value: ". $user{$key} ."\n"; };</syntaxhighlight> |