Solved

For RobWMartin or  thoellri......

Posted on 2000-02-14
6
138 Views
Last Modified: 2010-03-05
Hi Guys,

Well, I got to playing around some more and got a few bits running ok, and certainly understand it some more, and have been making some sense of Tobias' code (from the other question). I've been ripping bits and pieces out as I needed, but am not familiar with hash arrays etc. This is the code which I've turned it into, just to play with:

#!/usr/bin/perl

use strict;
use DBI;

my $dbi_db             ="xxxxxx";
my $dbi_user           ="xxxxxx";
my $dbi_passwd         ="xxxxxx";
my $dbi_datasource     ="dbi:mysql:$dbi_db";
my ($DBH);

$DBH = DBI->connect($dbi_datasource,
                    $dbi_user,
                    $dbi_passwd,
                    { PrintError => 0 }
                   ) || die "Can't connect to database! - $DBI::errstr";

   my($sth)=$DBH->prepare(qq{select * from test WHERE Name=FatBoy});
   $sth->execute;
   while(my $href=$sth->fetchrow_hashref)
      {
      foreach (keys %$href) { print "$_: $$href{$_}  \n";}
      print "\n";
      }

which works ok, but now I want to know how to get the key values into other variables. Just supposing I have three column names, (e.g. Name, Birth, Sex), how do I then get those into three variables called $name, $birth and $sex.

Actually, I'm kinda curious about the whole line which goes:
...keys %$href) { print "$_: $$href{$_}...

could you maybe explain the %$href and the $$href. I can see what it's doing, but don't quite follow the syntax.

Any help very welcome,
Thx in advance,
D
0
Comment
Question by:dgb001
  • 3
  • 3
6 Comments
 
LVL 3

Expert Comment

by:RobWMartin
ID: 2519781
If you are familiar with C, then a hashref, or any ref for that matter, is like a pointer.  If you're familiar with Visual Basic, it's like a reference, a la pass by reference, for function calls.  Basically, it holds the address, so to speak, of the hash rather than the hash itself.  To use the hash, you have to dereference it.  Putting the % in front of $href, dereferences $href, giving you the hash.  Putting the $ in front, dereferences to a scalar value (e.g. a specific string) contained in the hash. In this case, you must be specifying an index into the hash that pulls out a specific value (i.e. scalar).  Thus, the {}.  Without references, it's easier to see the relationship between % and $:

my %hash;
$hash{'key1'}="value1";
$hash{'key2'}="value2";
foreach $key ( keys %hash ){
  print "$key has a value of $hash{$key}\n";
}

When you want to deal with the hash as a whole, you use the %, as in the foreach.  I.e. keys is a function which takes a hash and returns a list of its keys.  When you are accessing a value in the hash, using a key (like 'key1'), the result will be a scalar (not a hash), so you must use the $.  IOW, $ always means scalar, % always means hash, @ always means array.  So you might have noticed that the $href is a scalar.  References are always treated as scalar values, themselves, regardless of what they are a reference to.  

If you want to directly create a reference, you would do the following:

$href=\%hash;

The backslash says, I don't want the hash, I want a reference to it.

Hope that helps.  Now, to the real business.  You want some real values, Name, Birth, Sex.  Those are scalars, so just create some scalar variables, like so:

my $Name;
my $Birth;
my $Sex;

To get the values out of the hash, referred to by $href, you will need to do the following:

$Name=$$href{'Name'};
and so on.

Get a good book on perl, it's a wonderful language to use.  Using it effectively comes quick; mastering it can take a very long time, but it is an enjoyable experience.  Try the O'Reilly book, "Learning Perl."

G'luck
Rob
0
 
LVL 1

Author Comment

by:dgb001
ID: 2520041
Hmmm, yes a good book would be handy....unfortunately I just never get time to learn more than I actually need to know for the task at hand. Never mind. Maybe one day.

Well, I think I understand what you're saying, but don't seem to be having any success with it, I'm either getting no values into the variables, although it's just printed them from the hash loop code, or I'm getting an error. The error I get is:

Global symbol "$href" requires explicit package name at testdb.pl line 37.

which I guess means that I need to declare it with: my $href; at top of proggie, which I have done, as with the rest of the vars, but still no joy.

If I declare $href, then the script runs through without errors, but get no values. If I don't declare $href, or any of the others then it naturally falls over.

START.....

my $N1;
my $N2;
my $P1;

$DBH = DBI->connect($dbi_datasource,
                    $dbi_user,
                    $dbi_passwd,
                    { PrintError => 0 }
                   ) || die "Can't connect to database! - $DBI::errstr";

   my($sth)=$DBH->prepare(qq{select * from test WHERE N1=1940});
   $sth->execute;
   while(my $href=$sth->fetchrow_hashref)
      {
      foreach (keys %$href) { print "$_: $$href{$_}  \n";}
      print "\n";
      }

$N1=$$href{'N1'};
$N2=$$href{'N2'};
$P1=$$href{'P1'};

print "N1: $N1\n";
print "N2: $N2\n";
print "P1: $P1\n";

......END

any ideas...?

Thx for your help again,
D

0
 
LVL 3

Expert Comment

by:RobWMartin
ID: 2520080
You need to move the assignments inside the while loop:

 
while(my $href=$sth->fetchrow_hashref)
{
$N1=$$href{'N1'};
$N2=$$href{'N2'};
$P1=$$href{'P1'};
print "N1 is $N1\n";
print "N2 is $N2\n";
print "P1 is $P1\n";
}

Rob

0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 1

Author Comment

by:dgb001
ID: 2520105
ooohhhh!!!!

Okey dokey....give me a few mins and I'll be back in here again.

Thx,
D
0
 
LVL 1

Author Comment

by:dgb001
ID: 2520163
Yes, that's great - thanks a lot. I now have everything I need (I think) - actually I've learned quite a bit since 24 hours ago when I thought that a MySQL database was pretty much like a normal file which was just read in via some fancy footwork.

For the moment all I need to do is to be able to read from the database with a key value and output the data from the other fields, so I'm ok with that now, and together with your help earlier with squirting the sql-dump into MySQL then I think I have more than enough info to keep me going.

Just in case any other newbies happen upon this question, then I did find a couple of good tutorials on the web, but one of the better ones was at:
http://www.inlink.com/~perlguy/sql/ , just in case (like me) you need a few pointers.

Well, many thx Rob, and if you post something as an answer then I can disgorge myself of some points. :-)

Best wishes,
D
0
 
LVL 3

Accepted Solution

by:
RobWMartin earned 50 total points
ID: 2520205
Actually, you can accept any comment as the answer.  There should be a link near the top of the comment, last I recall.

Glad things are working for you.

Later,
Rob
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now