Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

How can one sort array elements in different text files?

by supriyoch_2008 (Monk)
on Nov 05, 2019 at 16:52 UTC ( [id://11108334]=perlquestion: print w/replies, xml ) Need Help??

supriyoch_2008 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perlmonks,

I am interested to sort the elements of an array by two's or three's in different text files within a folder. The array is @array=qw/a b c d e f g h i/; within the "result" folder the text file 1.txt should contain a b; 2.txt should contain c d; 3.txt should contain e f etc. I have written a code but it does not give the desired results. I welcome suggestions from perlmonks to solve this problem.

Here goes my code:

#!/usr/bin/perl use warnings; use strict; my @array= qw/a b c d e f g h i/; my $size= 2; # Number of elements in each text file my $count= @array; my $file_num1= $count/$size; my $integer= int$file_num1; my $file_number= $integer+1; # maximum number of files print "\n Number of text files: $file_number\n"; # To create a result folder on desktop: my $dir="Result"; mkdir $dir or die $!; # code to sort two elements in each text file: my $num1=0; for (@array) { $num1++; # for LOOP begins # code to be written to place $size elements in each file # To create the text files like 1.txt, 2.txt inside Result folder: #################################################### my $output="$dir/$num1.txt"; open (my $fh,">",$output) or die"Cannot open file'$output'.\n"; ############################################### # print $fh ?? close $output; } # for LOOP ends exit;

I got the results as follows with the creation of a Result folder containing 9 text files i.e. 1.txt ... 9.txt:

C:\Users\x>cd d* C:\Users\x\Desktop>p.pl Number of text files: 5 C:\Users\x\Desktop>

The expected Result folder must contain 5 text files with two elements like:

1.txt a b 2.txt c d .. 5.txt i

Replies are listed 'Best First'.
Re: How can one sort array elements in different text files?
by choroba (Cardinal) on Nov 05, 2019 at 17:00 UTC
    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]

      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.

      Hi choroba,

      Thank you very much for your suggestions.

Re: How can one sort array elements in different text files?
by 1nickt (Canon) on Nov 06, 2019 at 01:16 UTC

    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.

      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.

      Hi lnickt,

      Thank you for your suggestions.

A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11108334]
Approved by haukex
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-25 17:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found