#!/usr/bin/perl -w use strict; use warnings; sub get_data { # here we simulate the expensive operation # of loading data into the hash my $idx = shift; print "retrieving data for $idx...\n"; return "value for $idx"; } my $result; my %cache; foreach (1,2,4,16,32,2,64,1,2) { # here we are asking for values from the cache # (hash), and if they aren't there, we get them # from the file. $result = $cache{$_} ||= get_data($_); print "$result\n"; }