mtaivalmaa has asked for the wisdom of the Perl Monks concerning the following question:

I can't get the $ans to return any value when used in the $myhash{$ans,'price'}; statement. The first part print $ans . "-" works fine. Why wont the $ans variable work in the function? I have tried a static variable and it works fine. Thanks Mike ************************************************ #!/usr/bin/perl use Finance::Quote; open (SLIST,"</scripts/test.txt"); @stocks = <SLIST>; close (SLIST); $q = Finance::Quote->new; $cc = 'usa'; $symb = 'WTVN.PK'; %myhash = $q->fetch($cc,@stocks); foreach $ans (@stocks){ print $ans ."-". $myhash{$ans,'price'}; }

Replies are listed 'Best First'.
Re: Finance::Quote; and foreach
by runrig (Abbot) on Apr 03, 2006 at 05:48 UTC
    chomp your stock symbols:
    chomp(@stocks = <SLIST>);
    Finance::Quote returns the data even though you have the linefeeds, but your for loop does not access the data because the hash keys returned from fetch() do not have linefeeds.
      chomp ROCKS!! Thanks for the help it worked great!
Re: Finance::Quote; and foreach
by bowei_99 (Friar) on Apr 03, 2006 at 06:02 UTC
    Your code worked for me. I used it to look up Google's stock, and got a correct value of 390.

    I think your problem lies in your file - for some reason, perl isn't reading in the values from the file as you expect it would. Since you (and I) hard code a variable, and it works fine, plus the fact that I don't know what your /scripts/test.txt file looks like, I suspect it's something with that file.

    Here's the code I got to work, with comments. I included some code you can run to help confirm if it's reading in the contents of the file correctly.

    #!/usr/bin/perl use Finance::Quote; use Carp; # This should give you more info if it couldn't read the file open SLIST, <, "/scripts/test.txt" or croak "Cannot open file - $!\n"; @stocks = <SLIST>; close (SLIST); # This will confirm that the stocks read in from the file are # what you expect print "Checking stocks: "; for my $stock (@stocks) { print "$stock "; } print "\n"; # the following code (uncommented) worked fine for me. # It got google's stock quote correctly #@stocks = ("GOOG"); $q = Finance::Quote->new; $cc = 'usa'; $symb = 'WTVN.PK'; # What is this used for? If not needed, good to d +elete it %myhash = $q->fetch($cc,@stocks); foreach $ans (@stocks){ print $ans ."-". $myhash{$ans,'price'}; }

    -- Burvil

      If you actually read the data from a file instead of hardcoding the symbol in the program, you would see the problem (that the data coming in from the file has linefeeds).