Melb.pm meetings
Scott Penrose
scottp at dd.com.au
Fri Jan 11 01:14:30 CST 2002
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Friday, January 11, 2002, at 05:50 , Andrew Gray wrote:
> could someone kind please tell me how to sort a hash table
> ie I have the following code fragment, sorry if it's not elegant, I'm
> not a
> perl guru (yet!)
> and I want to sort by ip number so the file gets written ordered.
>
> open(LOG, "> deny.log") or die("Cant open deny.log for writing\n");
> foreach $ip (keys %denylog)
in theory you can just do
foreach my $ip (sort keys %denylog) {
And that will sort your keys nicely, but it is alphabetically, not by IP
number. eg:
100.1.1.1
2.3.3.3
2 would come after 100. What you really probably need to do is turn it
into a 32 bit integer (does anyone remember the method?)
You can think of arrays just like piping on the command line. %denylog
returns pairs, key, value for each entry in the hash. keys returns the
first of these (where as values returns just the values of each) then
sort sorts those keys, you can add other things like grep and more.
Also you can pass a sub... eg:
foreach my $ip (sort {Net2Int($a) <=> Net2Int($b)} keys %denylog) {
Of course you would have to have a sub Net2Int. $a is always the first
and $b in a bubble sort being automatically run by sort.
Scott
> {
> ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) =
> localtime($denylog{$ip});
> $year+=1900;
> $human_time=$year."/".$mon."/".$mday." ".$hour."\.".$min;
> if ( ($time-$denylog{$ip}) < $expire_time )
> {
> print LOG ($ip,":",$denylog{$ip},": ",$human_time,"\n");
> } else {
> # print "$ip was removed from deny list as it is too
> old\n";
> $deny_list{$ip}=''; # remove it from the %deny_list
> as
> it has aged out of list
> }
> }
> close(LOG);
>
>
> regards
>
> Andrew Gray
> Systems Administrator, NetConnect Communications
> sysadmin at netconnect.com.au
>
>
>
>
>
- ---
Scott Penrose
Open source and Linux Developer
http://linux.dd.com.au/
scottp at dd.com.au
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (Darwin)
Comment: For info see http://www.gnupg.org
iD8DBQE8PpDbDCFCcmAm26YRAtjiAJ91IC+5vrln219SohKOpFDQT4O5EgCfeV+T
4PqIyRrJovE9xyiyFzk/oj4=
=VNdS
-----END PGP SIGNATURE-----
More information about the Melbourne-pm
mailing list