use IO::File; my %Handles; while (<>) { my $handle = $Handles{length} ||= IO::File->new(">" . length - 1); print $handle $_; } # This is unnecessary unless you're anal (like I try to be) $_->close for values %Handles;