A bit of Perl fun

davidbrit2

Licensed Computer Geek
See if you can figure out what my program does: (Specifically, HOW it does it)

Code:
#!/usr/bin/perl -w
@d=@ARGV;sub s{my($f,$l)=@_;if($f<$l){&s($f,my($m)=int(($f+$l)/2));&s($m
+1,$l);@c=();@_=(@d[$f..$m],reverse@d[$m+1..$l]);while(@_){push@c,($_[0]
<$_[-1])?shift:pop}@d[$f..$l]=@c}}&s(0,@d-1);print"@d\n";

After you've done that, see if you can do it in fewer characters. :-)


I need to stop hanging around comp.lang.perl.misc. It's obviously affecting my sanity.
 
Code:
#!/usr/bin/perl -w
foreach(sort{$a<=>$b}@ARGV){print"$_ ";}print"\n";

How about that? :)

What you did is fun recursion to sort a numbered list, numerically, by using an array, and splitting it apart, and ordering it while going thru it. Not up on my sorting algorithms as of late, but it appears to be a recursive quicksort, or something of the sort :) Ofcourse, if what you wanted was a shorter bit of code to do your algorythm, that can be done too :) But I'm out of time, time to go to the bar :)

The question is, will this fry your brain:


Brian


s^^/hfe/ova/znvy ^;s!$!ogbarvyy\@crey.arg!;y+a-zA-Z+n-za-mN-ZA-M+;open(F,"|$_")
;s*$_*Fhowrpg: jurr!\n\n\n*;y~a-zA-Z~n-za-mN-ZA-M~;print F;while(<>){print F}
 
Heh, that's some pretty impressive use of the good ol' transliteration operator. I just love how easy it is to ROT13 with perl. :-)

I didn't realize that prepending a file name with a pipe in an open statement would create a named pipe for output. That should come in handy, especially if there's an equivalent for grabbing the STDIO of a process just as easily...

And the sort algorithm is mergesort, but I went a slightly non-standard route and used a single array to store both unmerged halves, back to back. I just love being able to pop/shift off of either end of an array. Beat that, Java! :-)
 
Yeah, using open(FILE,"|/command"); will allow you to get all the output, but you can't do the same for input. You can attempt it, but it's really really not recommended. To many issues come up with blocking/etc when trying to read and write from a process without special things put into place. If you really want to do i/o with a running process, take a look at the Expect perl module. Its basically a perl implementation of the expact language. Works really really well for doing i/o with running apps.

Brian
 
Back
Top