A better way . . .

Randal L. Schwartz merlyn at stonehenge.com
Fri Dec 14 13:49:12 CST 2001

>>>>> "mikeraz" == mikeraz  <mikeraz at patch.com> writes:

mikeraz> To which I replied:

mikeraz> Why yes, someone would:

mikeraz> :.!perl -ne '(@i)=split /\"/; (@w)=split / /, $i[1]; print "$i[0]\"", (join " ", sort @w), "\"";' 

mikeraz> 	or
mikeraz> :.!           # send current line to 
mikeraz> perl -ne '    #perl treating the following string as the contents of a while(<>){ ... } loop
mikeraz> (@i)=split /\"/;       # cut the line up based on quotes
mikeraz> (@w)=split / /, $i[1]; # cut the stuff up between the quotes based on spaces
mikeraz> print "$i[0]\"",       # print the begining of the line and the opening quote
mikeraz> (join " ", sort @w),   # and the sorted space reinserted data
mikeraz>  "\"";'                # and the closing quote

mikeraz> So Real Perl People, what is a better way to do this?

:.!perl -pe '$x = $_ =~ s/^(\w+)="// and $f = $1 and $x =~ s/"\s*$// and @w = sort split " ", $x and s/.*/$f="@w"/'

This sorts the words, and doesn't change the string if something unexpected
is on the line.

mikeraz> :'<,'>!perl -ne '(@w)=split; print join " ", sort @w;'

mikeraz> Which would cause:
mikeraz>   SERVICES="mysql postgresql bind9 jabber nfs-kernel-server nfs-user-server samba apache ssh ntp inetd exim sendmail"  

mikeraz> to become:
mikeraz>   SERVICES="mysql apache bind9 exim inetd jabber nfs-kernel-server nfs-user-server ntp postgresql samba sendmail" ssh 

You sorted the pieces.  sendmail" comes before ssh.  The first element
is SERVICES=" which is uppercase, sorting before lowercase.

Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!

More information about the Pdx-pm-list mailing list