#!/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"; } #### retrieving data for 1... value for 1 retrieving data for 2... value for 2 retrieving data for 4... value for 4 retrieving data for 16... value for 16 retrieving data for 32... value for 32 value for 2 retrieving data for 64... value for 64 value for 1 value for 2