Questions about this topic? Sign up to ask in the talk tab.

Perl/Basics/Hashes/

From NetSec
Revision as of 00:41, 19 July 2012 by Chantal21I (Talk | contribs) (Created page with "A hash is very similar to a struct in C. ====Introduction==== {{:Perl/Basics/Hashes/Introduction}} ====Helper Functions==== {{:Perl/Basics/Hashes/Helper_Functions}}")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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>