Date: Fri, 29 Jun 2001 17:03:34 +0200 From: Patrick Erler Subject: Re: converting shell "sort" command to perl.. Message-Id: Benjamin Goldberg wrote in news:3B3C1A30.54DC5E6 @earthlink.net: > Patrick Erler wrote: >> now i want to convert the script to perl, no big problem, but this >> command i just don't get converted: >> >> sort -k 4.9b,4.13n -k 4.5b,4.7M -k 4.2b,4.3n -k4.14b,4.15n >> -k 4.17b,4.18n -k 4.20b,4.21n >> >> what it sorts is a simple apache log like this: >> 213.83.52.132 - - [28/Jun/2001:20:29:43 +0200] "GET / HTTP/1.0" 200 >> 3392 "-" "check_http/1.32.2.6 (netsaint-plugins 1.2.9-4)" >> >> ok, i could call the shell but i really would like to do it in perl... [Benjamins code deleted] > I could have used Time::Local rather than packing the date components as > bytes, but there is no need to bring it in, since it isn't really > needed. > > Note that this code is untested. thanks benjamin.. i corrected some bugs in the code.. here is a tested version: #!/usr/bin/perl -w use strict; #$#ARGV >= 1 or die "Usage:\n\t$0 [logfile]\n"; my %mon; @mon{qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)} = (0..11); my $stabilizer = 0; open my $ifh, "<", $ARGV[0] # my $ifh closed at end of do-block. or die "Could not open $ARGV[0] for r: $!\n"; rename( $ARGV[0], $ARGV[0] . ".bak" ) or die "Could not rename $ARGV[0] to $ARGV[0].bak: $!\n"; open my $ofh, ">", $ARGV[0] # note there is no "my" here. or die "Could not open $ARGV[0] for w: $!\n"; print $ofh substr $_, 11 for sort map { # 213.83.52.132 - - [28/Jun/2001:20:29:43 stuff m/^\S* \S* \S* (\S*)/; my @date = unpack "xa2xa3xa4xa2xa2xa2", $1; pack "ncccccNa*", $date[2], $mon{$date[1]}, @date[0,3,4,5], ++$stabilizer, $_; } do {{ # double leftbrace to make a block ($ifh, $ofh) = (*STDIN, *STDOUT), last if @ARGV == 0; } # end of block; "last" from above skips to here. <$ifh>; }; close $ofh or die "Couldn't close $ARGV[0]: $!\n" if @ARGV == 1; __END__ only the simplest thing with this code i don't get solved right now.. how should this line look like correctly? $#ARGV >= 1 or die "Usage:\n\t$0 [logfile]\n"; thanks benjamin, you've been a great help! -- PAT vcard/LDAP/PGP: http://dresden-online.com/perler/identity.html PGP fingerprint: DAC6 2FDA 1ED7 AD55 BD1F 5142 3D5F 72BF Yahoo-ID: perler - http://jpager.yahoo.com/jpager/messenger.html