my $fullpath = $file; # Not just the number, but e.g. "7893.jpg" $fullpath =~ s|(\w{1,3}).*|join('/',split(//,$1),$&)|e or die "Bad filename $file";