Click to See Complete Forum and Search --> : Can I make this smaller?


eXtremist
03-23-2001, 10:14 AM
[ 25 March 2001: Message edited by: eXtremist ]

YaRness
03-23-2001, 10:29 AM
this is the shortest, code-wise, way i can think of to do it. i'm not opening a file however, i'm using redirection (ie "script < inputfile"), but i'm sure it can be easily modified.


undef $/;
print join(' ',reverse(sort(split(/[^a-zA-Z0-9]/,<> ))));

you can adjust the [^a-zA-Z0-9] bit for whatever you want to allow in your words. this basically splits the file up long any string or character that isn't in that set.

eXtremist
03-23-2001, 11:12 AM
hey.. that's cool..

what does the undef $/ do?

sorry, I just started PERL a week ago.

eXtremist
03-23-2001, 11:18 AM
Hmm... I modified it to use a filehandle, then stuck it in my code but I get nothing like I am supposed to get.. :(

TheLinuxDuck
03-23-2001, 03:45 PM
eXtremist:

This is about the best you're going to get:

/home/root/perl/extremist> cat file.pl
#!/usr/bin/perl -w
use strict;
use warnings;

undef $/;
print join " ", reverse sort split /[\s*|\n*]/, <>;
print "\n";
/home/root/perl/extremist> cat file.data
bacon is good for me to eat
/home/root/perl/extremist> ./file.pl file.data
to me is good for eat bacon


$/ is generally always set to a newline, or \n. When you read a line from a file, such as

while(<INFILE> )
#
# or
#
$oneLine=<INFILE>;

the read will stop when it finds the character at $/. If you undefine it, the file will not stop per line, but read the entire file in on one line, instead of multiple lines.

And, when <> is used as YaR and I did, per l automatically tries to read from the command line. If no arguments are present, it will read from STDIN.

Perl is qool.. :)

eXtremist
03-27-2001, 08:20 AM
Thanks.. This is cool.. But it doesn't preserve line length.

If I have a file with 2 lines, I have to read in all the words, then the output must match the input (ie. 2 lines, same # of words on each).