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

Hi experts, I have one thing to finish this morning but my vpn is down and I can't get to my database. I wrote and tested the below piece of code last Friday and I didn't get the desired output. (I'm a Perl beginner BTW) The file was created and the correct number of lines were written to it. The output was not the key:value pairs I was trying to get from the MySQL database. Since I got the correct number of lines I am thinking I have a problem in my references in the foreach loop. Each line that did get written consisted of numbers 83208512 (I can't get to the network so I don't know how many) and there was one line for every record I expected.
my $query = "SELECT blah blah stuff to get"; my $sth = $dbh->prepare($query) or die "Can't prepare: $query. Reason: + $!"; $sth->execute($user_id)or die "Can't execute: $query. Reason: $!"; open( DATAOUT, ">$filename" ); while ( my $ref = $sth->fetchrow_hashref() ){ foreach ( keys (%{$ref}) ) { print DATAOUT "$_"+":"+"$ref->{$_}\t"; } print DATAOUT "\n"; };
Could you please take a moment and straighten me out with regards to my references. Thanks. rightfield P.S. - My vpn's been down over an hour now, so I don't think its coming back up soon that's why I asking for help instead of just banging at it until I get it right. Without a database at home I'm on hold. Maybe I'll spend my time installing MySQL and get a database at home.

Replies are listed 'Best First'.
Re: hashref and references
by kwaping (Priest) on May 22, 2006 at 15:22 UTC
    Your use of references looks fine to me. I think this line contains the actual error:
    print DATAOUT "$_"+":"+"$ref->{$_}\t";
    You're using Java syntax, not Perl. Try this instead:
    print DATAOUT $_ . ":" . $ref->{$_} . "\t";
    Unless of course you really do want to add up the strings, instead of concatenate them! :)

    ---
    It's all fine and dandy until someone has to look at the code.
Re: hashref and references
by davorg (Chancellor) on May 22, 2006 at 15:23 UTC

    + isn't the concatenation operator in Perl. You want . (a dot). Actually, here you just need to interpolate your values into your string.

    print DATAOUT "$_:$ref->{$_}\t";
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: hashref and references
by rightfield (Sexton) on May 22, 2006 at 15:47 UTC
    Hello experts, I got my own answer: print DATAOUT "$_:$$ref{$_}\t"; That's the way the print should have been done. (My vpn is back up so I could try something similar I found in a book.) I hope you're there next time I really need help. Thanks, rightfield