%hash = ( "view0" => [qw/buffersize size value/], "view1" => [qw/buffersize size value/], "view2" => [qw/buffersize size value/], "view3" => [qw/buffersize size value/]); my $lastview; my $output; foreach $key (sort(keys %hash)){ # Do this only the first time. if(not defined($lastview)){ $lastview = $key; $output = "$key"; next; } $output .= " full outer join $key on $lastview.$hash{$lastview}[1] = $key.$hash{$key}[1] and $lastview.$hash{$lastview}[0] = $key.$hash{$lastview}[0]"; $lastview = $key; } print $output, "\n";