XE.com From The Command Line

xe.com is a well known site for calculating the exchange value between the currencies of the world. However, there are times I’d prefer to query it from the command line. They have an API, but it’s not free, so I ended up writing a quick and dirty script that scrapes the web page and uses regexps to extract the data.

I know you’re not supposed to parse HTML with regexps, but sometimes, you can get away with it for a while. Also, this script is not that serious, so it can fail without hurting anything.

    #!perl
    use strict;
    use warnings;
    use feature 'say';
    use WWW::Mechanize;
    use Data::Dump qw(pp);

    sub url {
        my ($from, $to, $amount) = @_;
        my $tmpl = "https://www.xe.com/currencyconverter/convert/?Amount=%f&From=%s&To=%s";
        sprintf($tmpl, $amount, $from, $to);
    }

    sub get_xe_page {
        my ($from, $to, $amount) = @_;
        my $mech = WWW::Mechanize->new();
        my $url = url($from, $to, $amount);
        $mech->get($url);
        $mech->content;
    }

    sub extract_price {
        my $html = shift;
        my $r = qr|([\d,.]+)<span class="faded-digits">(\.?\d+)|;
        my @p = ($html =~ $r);
        my $price = join('', @p);
        $price =~ s/,//;
        $price;
    }

    sub main {
        my ($from, $to, $amount) = @_;
        my $c = get_xe_page($from, $to, $amount);
        my $p = extract_price($c);
        say "$amount $from = $p $to";
    }

    unless (caller) {
        main(@ARGV);
    }

Example

    > xe.pl HKD USD 500
    500 HKD = 64.145545 USD

Leave a comment

About gg

user-pic I blog about Perl.