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

I am running the following code:
use strict; use OLE; my $Conn; my $RS; $Conn = CreateObject OLE "ADODB.Connection"; #Create a connection f +or MS-SQL $Conn->Open("DSN=WIN;UID=db;PWD=passwd;"); #Open the ODBC named WIN $RS = $Conn->execute("select user from accounts where user = 'test'"); if (!$RS) { my $Errors = $Conn->Errors(); my $error; foreach $error (keys %$Errors) { print $error->{Description}, "\n"; } } else { print "The username is $RS->Fields(0)->value.\n"; } $Conn->Close;
When this code runs, I get the output:

The username is OLE=HASH(0x827ea0)->Fields(0)->value.

That is, it is resolving the value of the $RS->Fields(0)->value to an OLE hash of some kind. What I want is the value of that field. I looked around on PerlMonks, and found exactly the same code snippets but no discussion on this phenomenon.
This is running on Windows2000 connecting to MS-SQL7 with ActiveState Perl.


Replies are listed 'Best First'.
Re: Weird Results From MS-SQL Value
by arturo (Vicar) on Feb 14, 2001 at 23:12 UTC
    $rs is a reference, and in the double-quotes, its value gets printed out, as requested -- what Perl interprets your print as :"print the value of $rs, then the string "->fields(0)->value"...

    Believe it or not, this is Working as Advertised, but it's one of the gotchas when dealing with objects (and, more generally, references).

    My usual way of getting around this is to either use :

    printf "The username is %s\n", $rs->fields(0)->value;

    or print out a list:

    print "The username is ", $rs->fields(0)->value, "\n";

    There's another way where you can just wrap the whole thing in a set of double-quotes, but I always forget the syntax of it ... (print "@{ [ $obj->method ] }", but (a) it looks nasty (b) it will confuse you and (c) It looks REALLY NASTY =). I think the only reason it's there is to scare people about Perl syntax ... >=)

    Philosophy can be made out of anything. Or less -- Jerry A. Fodor

      Yea, I just got that about a minute ago. I changed the line
      print "The username is $RS->Fields(0)->value";
      print "The username is " . $RS->Fields(0)->value;
      And now it is working like a charm. Thanks.

Re: Weird Results From MS-SQL Value
by zeno (Friar) on Feb 14, 2001 at 23:17 UTC
    Replace the printout line with this:
    print "The username is ".($RS->Fields(0)->value).".\n";
    Then your result will get interpreted correctly. -zeno