Perl hash sort - How to sort a Perl hash by the hash key

Perl hash sort FAQ: How do I sort a Perl hash by the hash key?

Answer: Sorting the output of a Perl hash by the hash key is fairly straightforward. It involves two Perl functions, keys and sort, along with the good old foreach statement.

Perl environment variables - How to access Perl environment variables

Here's a quick example program that demonstrates how to access environment variables from within your Perl programs:

# environment variables are held in the %ENV hash
foreach $key (sort keys %ENV)
  print "$key is $ENV{$key}\n";

Using this simple Perl foreach loop, here's a subset of the output this script prints on my MacBook Pro:

Perl hash remove - How to remove an item from a Perl hash

Perl FAQ: How do I remove an item from a hash?

Answer: Use the Perl delete function.

The general syntax you need to use is shown here:


If you'd like more details and examples, read on...

Perl hash - remove/delete element example

Here's a complete example where I show both how to create and print a Perl hash, and then show how to remove elements from the hash using the Perl delete function:

How to add an item to a Perl hash

Perl hash FAQ: How do I add an item/element to a Perl hash?

Answer: Adding an item to a Perl hash is just like creating a Perl hash initially. Just assign the new item to the hash with the correct syntax, and you're in business.

In the following sample code I show how this is done by creating a hash named prices. The hash key is the name of a product, like pizza, and the hash value is the price of that product. Here's my Perl hash sample code:

How to print a Ruby hash sorted by value

I recently needed to print the information in a Ruby hash, with the results sorted by value. Here's a general recipe on how to print the hash results sorted by value. I've created a sample hash, and populated the hash with sample data, to show how this works.

First, here's the sample code, using the first name of each person as the key, and the last name as the value of the key/value pair:

Perl CGI environment variables example

Here's a sample Perl CGI program I wrote that prints out all of the environment variables it knows. I've found this program to be very useful when first installing a web server, or when debugging a problem with a web server or new environment.

Perl CGI environment variables - example program

Here's the code: