use strict; use Data::Dumper; my %hash; while () { chomp; s/\//}{/g; eval "\$hash".substr($_,1,length)."} = undef"; } print Dumper(\%hash); __DATA__ /root/dir1/file1 /root/dir1/file2 /root/dir1/file3 /root/dir2/file1