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

Hi, see Path::Tiny for file handling and splice for chopping chunks off an array.

use strict; use warnings; use feature 'say'; use Path::Tiny; my @array = ('a'..'i'); my $size = 2; my $file = 0; path( sprintf('%s.txt', ++$file) )->append( map {"$_\n"} splice(@array +, 0, $size) ) while @array; say "$file files"; __END__

Hope this helps!


The way forward always starts with a minimal test.

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

    While I use code like that frequently in Perl for "one off" scripts and love Perl for the ability to do it, for demonstrating technique to someone learning the trade there is just too much to unpack to be useful. How about:

    ... while (@array) { my @part = splice @array, 0, $size; my @lines = map {"$_\n"} @part; my $fileName = sprintf '%s.txt', ++$file; path($fileName)->append(@lines); }

    instead?

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

      One learns most by reaching beyond one's grasp.

      I post code like this so that beginners can quickly see that there are tools for most things, even if they can't grok the code at once.

      I am very glad that you posted the breakdown (although my goal was that the OP would "unpack" it him/herself) as it is surely important to understand what's really going on. Your demo is very important. My angle is honed by having worked with, hired, etc. too many Perl programmers who are so unfamiliar with standard modern tooling that they write krufty hand-rolled code that's hard to maintain.

      I hope to inspire beginners to always be considering that there may be a better tool for some functionality than trying to reinvent the wheel (even if reinventing a couple is a necessary beginning step).



      The way forward always starts with a minimal test.
Re^2: How can one sort array elements in different text files?
by supriyoch_2008 (Monk) on Nov 06, 2019 at 07:32 UTC

    Hi lnickt,

    Thank you for your suggestions.