Home arrow Perl Programming arrow Page 4 - Perl Hashes

Printing All the Values or Keys in a Hash - Perl

Thanks for stopping by for this seventh part in the series on Perl Lists and Hashes. Here we will discuss working with a new way to store data known as a Hash. We'll cover the basics, such as how to create them, and how to locate data within them. You'll learn to add records, remove records, and much more. If there is time, we will also cover multidimensional lists.

TABLE OF CONTENTS:
  1. Perl Hashes
  2. Creating A Hash
  3. Printing from a Hash
  4. Printing All the Values or Keys in a Hash
  5. Alternative Methods for Creating Hashes
By: James Payne
Rating: starstarstarstarstar / 6
April 28, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

As we saw earlier, you cannot simply print all the values in a hash using the print command. You could, but then you would also get the keys associated with those values as well, which you may not want. Perl has a handy function, called “values,” that can help you achieve this goal:


#!/usr/bin/perl

%HowItIs = (Dumb,'You ', Fat,'YoMama ',UglyGenius,'James Payne

',Nerd,'James Payne ');

print values(%HowItIs);

This prints out just the values in the hash:

  James Payne James Payne YoMama You

If we wanted to print out all the keys, and not the values, we can do that also, using another function, “keys”. Here it is in code:


#!/usr/bin/perl

%HowItIs = (Dumb,'You ', Fat,'YoMama ',UglyGenius,'James Payne

',Nerd,'James Payne');

print sort(keys(%HowItIs));

Note that I sorted this print out also:

  DumbFatNerdUglyGenius

And of course if we wanted a list of both keys and values in a sentence, we can do that as well with the following nifty little program:


#!/usr/bin/perl

%HowItIs = (Dumb,'You ', Fat,'YoMama ',UglyGenius,'James Payne

',Nerd,'James Payne');

@All = keys(%HowItIs);

foreach $ItIs(@All)

{print "The key for $HowItIs{$ItIs} is $ItIsn"};

Which gives us the following result:

  The key for James Payne is Nerd

  The key for James Payne is UglyGenius

  The key for Yomama is Fat

  The Key for You is Dumb



 
 
>>> More Perl Programming Articles          >>> More By James Payne
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: