Examples: Perl/File

Example #1

#!/usr/bin/perl
use strict;
use XML::Simple;
use Seach::Binary;
{
my $last_pos = 0;
sub read_elem {
	my $hnd = shift(@_);
	my $addr = shift(@_);
	my $pos = shift(@_);
	if ($pos) {
		$last_pos = $pos;
	} else {
		$pos = $last_pos;
	}
	seek($hnd, $pos*10+4, SEEK_SET);
	read $hnd, $end_num, 4;
	if ($addr>$end_num){
		return (1,$pos);
	} elsif ($addr<$end_num) {
		return (-1,$pos);
	}
	return (0,$pos);
}
}
my $countries = XMLin('/path/to/cwhois.xml', ContentKey => 'text');
$arr = stat('/path/to/cwhois.cwb');
$size = $arr[7];
open(CWBFILE, '/path/to/cwhois.cwb');
binmode CWBFILE;
@addr = split(/\./, $ENV{"REMOTE_ADDR"});
$num = (($addr[0]<<8 + $addr[1])<<8 + $addr[2])<<8 + $addr[3];
$pos = binary_search(0, $size/10-1, $num, 'read_elem', CWBFILE);
seek($hnd, $pos*10, SEEK_SET);
read $hnd, $start_num, 4;
if ($start_num<=$num) {
	seek(CWBFILE, $pos*10+8, SEEK_SET);
	read CWBFILE, $code1, 1;
	read CWBFILE, $code2, 1;
	$code = $code2<<8+$code1;
	$countries = @$countries{'country'};
	foreach $countries {
		my $country = @$_;
		if ($$country{'id'}==$code){
			print "Hello, you are visiting us from <B>".$$country{'text'}."</B>";
			last;
		}
	}
}
close CWBFILE;