Search code examples
perllistfilecountercopying

A simple copying code


I need a simple repeating code in pearl which reads from a file lets say txt inputs the data and then saves the new data in a another txt file . The code needs to do this :

In the first txt document we have some fruits in this format

  1. 2 apples
  2. 3 cherry's
  3. 4 tomatoes

so the code needs to do the following thing . Inputs 1. apples then it must recognize the second number which is the number of how many times it must write the word like this

  1. apples -> 1-1

           apples
    

    2 . apples -> 1-2

               apples
    

after that repeat the same process for every item of the list

for code I don't have an idea how to make it I know how to input the file and how to make the results file but that's about it

#!/usr/bin/perl\
open FH "<", "filename.txt" or die $!;

open FHWRITE, ">>results.txt" or die $!;

$fruit = 
 #dont know how for the $ to take the value of the first fruit 

$countnumb = split (' ',);

 # dont know how to take the second number for count number but i think its whit split 

$count =0; 

while ($count ne $countnumb)
{
    print "$fruit";
    $count++;
}

 # i dont know when this finishes how to make it go for the second fruit 

Solution

  • Some starting point

    while (my $line = <FH>){
      chomp($line);
      ### process the line
      #1. 2 apples 
      if ($line =~ s!^(\d+)[\.\s]+(\d+)\s+(.+?)$!!is){
        my ($line_no,$count,$text) = ($1,$2,$3);
        ### write out
        print FHWRITE $text for (1..$count); 
      } else {
         say "Cannot process $line\n";
      }
    }