in reply to How can one sort array elements in different text files?

You don't have to count the number of files, you can create them on the fly.
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my @array= qw( a b c d e f g h i ); my $size = 2; my $i = 1; while (@array) { open my $out, '>', "$i.txt" or die $!; say {$out} $_ for splice @array, 0, $size; ++$i; } say $i - 1, ' files created.';
map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: How can one sort array elements in different text files?
by GrandFather (Saint) on Nov 05, 2019 at 20:10 UTC

    Incrementing the count at the top of the loop is slightly cleaner:

    my $size = 2; my $i = 0; while (@array) { ++$i; open my $out, '>', "$i.txt" or die $!; say {$out} $_ for splice @array, 0, $size; } say "$i files created.";

    The point here is not optimisation, but to ensure $i has the right value wherever it is used. For a short piece of code like this the difference is not much, but add a few conditionals inside the loop and suddenly the semantics for $i can become rather uncertain.

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

      GrandFather,

      Thanks a lot for your suggestions. The code works and my problem is solved.

Re^2: How can one sort array elements in different text files?
by supriyoch_2008 (Monk) on Nov 06, 2019 at 07:28 UTC

    Hi choroba,

    Thank you very much for your suggestions.