sub write_vars { my $filename = shift(@_); my $vars = shift(@_); open(FILE, ">$filename"); foreach my $key (keys %{$vars}) { # this one is just for convienence my $i = \( $vars->{$key} ); # this is a switch statement # make a reference to $vars->{$key} and pass it to ref for (ref $i) { # if it is scalar, ref will return SCALAR... if (/SCALAR/) { print FILE "s:$key:" . $vars->{$key} . ";\n"; } # ...otherwise it returns an empty string # which means it is a hash or an array else { $j = $vars->{$key}; $type = ref $j; # if it is an array, print out each element if ($type eq "ARRAY") { print FILE "a:$key"; for my $element ( @{$j} ) { print FILE ":$element"; } print FILE ";\n"; } # likewise for a hash, print out the key/value pairs elsif ($type eq "HASH") { print FILE "h:$key"; for my $k ( keys %{$j} ) { print FILE ":$k," . $j->{$k}; } print FILE ";\n"; } } } } close(FILE); return; } %a = qw(One 1 Three 3); @b = qw(Foo Bar Baz Blah); %foo = ('a', \%a, 'b', \@b, 'c', 'C'); write_vars("test.txt", \%foo);