Please help me!I want the code for doing following task in perl. Task is that "Read the paragraph from a file and print it in another file in ascending(total number of words in a sentence) order." My sample task:
If the input "Hi! my name is Sarma. Can you help?"
Output should be "Hi! Can you hepl? my name is Sarma."                  
I could try this. It prints the number of words in a each sentence. My code is:


use strict;
use warnings;

my ($line,$inFile,$outFile,$para, $text, @sentences, @words, @length, $count, $i, $order);  #defined variables
$inFile = "name.txt";
$outFile = "out.txt";

open (SOURCE, $inFile) || die "cannot open \"$inFile\": $!";
open (RESULT, ">$outFile") || die "cannot open \"$outFile\": $!";

while ($line = <SOURCE>) {

$text = $text.$line;

close (SOURCE);

@sentences = split(/[!,?,.]/, $text);   #split text into sentences
for ($i=0;$i<scalar(@sentences);$i++)
@words=split(/\s+/, @sentences[$i]);    #split each sentence into words
@length = scalar(@words);   #count words of the sentence
my @array = sort @length;
print RESULT "@array\n";


close (RESULT);
Re: count words and print the sentences in an ascending order 80 80

Looks like your logic has a few problems.
1. You are iterating through the sentences but you are storing the words and lengths in arrays that will only contain a single element. (That is, you are overwriting the values in @words and @length on each pass because you aren't either indexing the array when you store them or adding them to the end of the existing arrays.)
2. Plus, you are sorting and printing this single item array each time you process a sentence when it seems you'd want to sort and print the results after processing all sentences.
3. It also seems that since you're only sorting and printing the length, you won't get the actual text printed.

Consider using a multi-dimensional array so you can easily associate the counts with the text.

Re: count words and print the sentences in an ascending order 80 80

Try this.
Using a hash and sorting by value

my $in="in";
my $out="out";
my $line;
my $text;
my @sentences;
my %seen;
open(SOURCE,"<in") or die $!."\n";
while ($line = <SOURCE>) {
$text = $text.$line;
@sentences = split(/[!,?,.]/, $text);

        my $dummy=$_;
        $dummy=~s/^\s//g;##removing any beginning space
#print hash as key value pair
#        print "$key => $value\n";
#sort hash by value

foreach $value (sort {$seen{$a} <=> $seen{$b} }
           keys %seen)
     print FOUT "$value\n";

cat out
Can you help
my name is Sarma

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.