(slightly OT): Python and linux - very cool
Mart van de Wege
mvdwege.usenet at drebbelstraat20.dyndns.org
Thu Aug 8 14:14:36 EDT 2002
On Thu, 08 Aug 2002 19:41:02 +0200, Just wrote:
> In article <o58uia-q8q.ln at drebbelstraat20.dyndns.org>,
> Mart van de Wege <mvdwege.usenet at drebbelstraat20.dyndns.org> wrote:
>
>> For example, this is what I recently did to extract all IPs from my
>> access.log:
>>
>> ----- BEGIN SCRIPT -----
>> #!/usr/bin/perl
>>
>> use warnings; # Make Perl picky about syntax.
>> use strict; # Make Perl *really* picky.
>>
>> my @iplist; # Declare an array to hold all IP addresses.
>>
>> open (FILE, '/var/log/apache/access.log');
>>
>> while (<FILE>) {
>> /^(\d+\.\d+\.\d+\.\d+)?/;
>> next unless $1; # Skip if the first field is somehow empty.
>> next if $1 eq '127.0.0.1'; # Skip localhost.
>> push @iplist, $1;
>> }
>> # @iplist now holds all IPs in the first field of access.log.
>>
>> ----- END SCRIPT -----
>>
>> Python can do this too of course, but somehow this is the sort of task
>> that comes naturally to me in Perl. Note the use of the regexp:
>>
>> 1. I don't have to explicitly declare and compile it.
>> 2. It operates on the default input variable ($_), so I don't have to
>> specify its target, I just use a bare regexp.
>
>
> import re
>
> iplist = []
>
> for line in open("/var/log/httpd/access_log"):
> m = re.match(r"^(\d+\.\d+\.\d+\.\d+)", line)
> if m:
> ip = m.group(1)
> if ip != "127.0.0.1":
> iplist.append(ip)
>
>
> I don't thinkthat's significantly worse (or better...) than the Perl
> version?
It isn't. Not at all.
I just like the way it's done in Perl better. <shrug>
Just a matter of taste I guess. You did miss one Perl advantage though:
the default variable. A lot of Perl operators can take that as input, and
it *can* make code cleaner and easier to write by eliminating temporary
variables (like 'line' in your example).
But again, it's a matter of taste. I like doing Gtk front-ends to my
scripts a lot better in Python, just as I like filtering files better in
Perl.
Mart
--
"Time expands and then contracts
When you're spinning in the grip of someone
Who is not an ordinary girl"
Counting Crows - Hard Candy
More information about the Python-list
mailing list