CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: Re: [yaroba] HELP: Edit Log



Kenosis
User

Mar 30, 2013, 9:28 AM


Views: 1190
Re: [yaroba] HELP

Perhaps the following will get you started:


Code
use strict; 
use warnings;

my @words;
my $shortest = my $longest = '';

while (<DATA>) {
for ( grep { $_ = uc; /^(?:A|B)/ } split /[\x20,.]+/ ) {
push @words, $_;
$shortest = $_ if length $_ < length $shortest or !$shortest;
$longest = $_ if length $_ > length $longest;
}
}

print "$_\n" for sort @words;
print "\nShortest: $shortest\nLongest: $longest";

__DATA__
I need a program that read file from disk, file contains of words that are separated by spaces, double spaces, commas and dots.
And the program selects only those words who starts with a or b letter and puts them to other file alphabeticaly.
Also finds longest, shortest words.


Output:


Code
A 
A
ALPHABETICALY
ALSO
AND
AND
AND
ARE
B
BY

Shortest: A
Longest: ALPHABETICALY


The code in the for() explained:


Code
grep { $_ = uc; /^(?:A|B)/ } split /[\x20,.]+/ 
^ ^ ^ ^
| | | |
| | | + - Split line on space (\x20), comma or period te get 'words'
| | + - Regex match: word begins with either "A" or "B"
| + - Convert to all upper-case
+ - If the regex successfully matches, let the 'word' pass from the split


Your specs say "words," and the above generates a list of word tokens, so you see some words repeated. However, if you want word types, you can use a hash instead of an array to keep track of those:


Code
use strict; 
use warnings;

my %words;
my $shortest = my $longest = '';

while (<DATA>) {
for ( grep { $_ = uc; /^(?:A|B)/ } split /[\x20,.]+/ ) {
$words{$_}++;
$shortest = $_ if length $_ < length $shortest or !$shortest;
$longest = $_ if length $_ > length $longest;
}
}

print "$_\n" for sort keys %words;
print "\nShortest: $shortest\nLongest: $longest";

__DATA__
I need a program that read file from disk, file contains of words that are separated by spaces, double spaces, commas and dots.
And the program selects only those words who starts with a or b letter and puts them to other file alphabeticaly.
Also finds longest, shortest words.


Output:


Code
A 
ALPHABETICALY
ALSO
AND
ARE
B
BY

Shortest: A
Longest: ALPHABETICALY


Hope this helps!


(This post was edited by Kenosis on Mar 30, 2013, 12:34 PM)


Edit Log:
Post edited by Kenosis (User) on Mar 30, 2013, 12:21 PM
Post edited by Kenosis (User) on Mar 30, 2013, 12:26 PM
Post edited by Kenosis (User) on Mar 30, 2013, 12:31 PM
Post edited by Kenosis (User) on Mar 30, 2013, 12:34 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives