Finance-Currency-Convert-BChile

 view release on metacpan or  search on metacpan

lib/Finance/Currency/Convert/BChile.pm  view on Meta::CPAN


use LWP::UserAgent;
use HTML::TokeParser;

# As of 2013-07-24, bcentral.cl uses an iframe in homepage and
# feeds values from another URL
my $BCENTRAL_URL = 'http://si3.bcentral.cl/indicadoresvalores/secure/indicadoresvalores.aspx';
my $DEFAULT_UA   = 'Finance::Currency::Convert::BChile perl module';

=head1 SYNOPSIS

Currency conversion module between Chilean Pesos (CLP) and USA
Dollars (USD). The conversion rate is obtained from the official
source in Chile: the central bank "Banco Central de Chile", from
their webpage http://www.bcentral.cl

    use Finance::Currency::Convert::BChile;

    my $conversor = Finance::Currency::Convert::BChile->new();
    $conversor->update;
    print $conversor->CLP2USD(20170);

=head1 FUNCTIONS

=head2 new

Creates a new Finance::Currency::Convert::BChile object.
Initializes the web robot. You can pass a user agent string
as a parameter.

=cut

sub new {
	my ($this, @args) = @_;

	my $class = ref($this) || $this;

	my $ua_string = $args[0] || $DEFAULT_UA;

	my $self = {};
	bless $self, $class;

	$self->{'ua'} = LWP::UserAgent->new
		or croak "Unable to create user agent";
	$self->{'ua'}->agent($ua_string);

	$self->{'dolar'} = '';
	$self->{'fecha'} = '';

	return $self;
}

=head2 update

Obtains the data from bcentral page.
You can pass a fake value as a parameter. In this case there's no
update from bcentral site.

=cut

sub update {
	my $self     = shift;
	my $simulate = shift;

	if ($simulate) {
		$self->{'dolar'} = $simulate;
		$self->{'fecha'} = 'UNKNOWN';

		return 1;
	}

	my $response = $self->{'ua'}->get($BCENTRAL_URL);

	unless ($response->is_success) {
		carp "Unable to get page: " . $response->status_line;

		$self->{'dolar'} = '';
		$self->{'fecha'} = '';
		return 0;
	}

	my $p = HTML::TokeParser->new(\$response->content)
		or croak "Unable to parse response: $!";

	my ($dolar, $fecha);

    while (my $token = $p->get_tag("div")) {
        next unless $token->[1]{id} eq 'ind-dia';

        while (my $token2 = $p->get_tag("p")) {
            next unless $token2->[1]{class} eq 'published-date';
            last;
        }
        while (my $token2 = $p->get_tag("span")) {
            next unless $token2->[1]{id} eq 'Lbl_fecha';
            last;
        }
        $fecha = $p->get_text;

        while (my $token2 = $p->get_tag("span")) {
            next unless $token2->[1]{id} eq 'RptListado_ctl03_lbl_valo';
            $dolar = $p->get_text;
            last;
        }
    }

	return 0 unless $dolar and $fecha;
    return 0 unless $dolar =~ /^\d+[,.]{0,1}\d+$/;

	$self->{'dolar'} = $dolar;
	$self->{'fecha'} = $fecha;

	return 1;
}

=head2 date

Return the date obtained from Banco Central's site.
There's no formatting at all.

=cut



( run in 1.965 second using v1.01-cache-2.11-cpan-600a1bdf6e4 )