Check your stocks with Perl

I wrote this small script to check the value of stocks with Perl. It doesn’t shows the value of the stock in the pre and post market, but it does its job.

     1  #!/usr/bin/perl -w
     2
     3  use strict;
     4  # Loading modules with use
     5  use LWP::UserAgent;
     6  use HTTP::Request;
     7  use HTML::Strip;
     8
     9  my $length = $#ARGV + 1;
    10  my $stock;
    11
    12  if ($length <= 0) {
    13          print "Usage: ./stock.pl ticker1 ticker2 .. tickern\n";
    14          exit 1 }
    15
    16  my $ua = LWP::UserAgent->new;
    17  #$ua->agent("Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");
    18  $ua->agent("Perl Script checking stock value");
    19
    20  # Getting Google finance site website
    21  foreach $stock (0 .. $#ARGV) {
    22  my $url = "http://www.google.com/finance?q=$ARGV[$stock]";
    23  my $req = HTTP::Request->new(GET => $url);
    24  my $response = $ua->request($req);
    25  my $content = $response->content();
    26
    27  # Splitting the HTML code previously requested
    28  my @values = split(' ', $content);
    29  my @valor = grep(/ref_(\d+)_l/, @values);
    30
    31  foreach my $val (@valor) {
    32          # Using HTML::Strip to clean HTML tag
    33          my $hs = HTML::Strip->new();
    34          my $clean_text = $hs->parse( $val );
    35          $hs->eof;
    36          # Using split to remove > 
    37          my @value_2 = split(/\>/, $clean_text);
    38                  # Printing stock value after removing >
    39                  print "$ARGV[$stock] price is $value_2[1]\n"; 
    40    }
    41  }

Here is an usage example.

xavi@liberdade:/tmp$ ./stockparse.pl ge cat
ge price is 16.05
cat price is 69.72
xavi@liberdade:/tmp$ 

Suggestions are always welcome.

Leave a Reply