PERL Array count on Array Reference
PERL has a lot of cool built in operators to find things like number of elements in an array an such ($#) which are very straight forward when using basic data types.
With C I never had a problem with the indirection associated with pointers and dereferencing. Of course, being the pedantic guy I am, I always used parentheses to excess.
Anyway, I was working on some code to retrieve as set of fields back from an Omnibus database and the database function returns a reference to an array of arrays. I only expect 1 row coming back, but I needed a quick way to tell that. With a little experimentation I found it was:
Here is a larger code chunk to put things in perspective, hopefully sanitized enough to be public:
With C I never had a problem with the indirection associated with pointers and dereferencing. Of course, being the pedantic guy I am, I always used parentheses to excess.
Anyway, I was working on some code to retrieve as set of fields back from an Omnibus database and the database function returns a reference to an array of arrays. I only expect 1 row coming back, but I needed a quick way to tell that. With a little experimentation I found it was:
$#$resultsPTRSure it is easy now, but I had to run through a few iterations to figure out just what $# wanted to see.
Here is a larger code chunk to put things in perspective, hopefully sanitized enough to be public:
#!/usr/bin/perl
#
# $Id$
#
use strict;
use warnings;
use diagnostics;
use POSIX ":sys_wait_h";
use lib "/packages";
require "Logging.pm";
require "NcDatabase.pm";
use NcDatabase qw(ncSetAlertsStatusSeverityZero ncSetAlertsStatusSeverityFive ncSetAlertsJournal);
sub main ()
{
my ($localhostname) = Sys::Hostname::hostname();
my ($dbserver) = NcDatabase::getDBServForHost($localhostname);
my ($dbinstance) = NcDatabase::getDBInstForHost($localhostname);
my ($dbuser) = NcDatabase::getMicroMuseDBUser();
my ($dbpass) =NcDatabase::getMicroMuseDBPass();
my ($SQLcommand) = 'select Serial,Summary from alerts.status WHERE Serial >= 5284627';
my ($resultsPTR);
Logging::setSyslogLevel ("debug");
Logging::enableSysloging ();
if ( defined($resultsPTR = NcDatabase::ncReadTableFromDb("$SQLcommand")) )
{
foreach my $row (@$resultsPTR)
{
print STDERR "results = " . join(',',@{$row}) . "\n";
}
}
print STDERR "\n\nresults2 = " . join (',',@{$resultsPTR->[0]}) . "\n";
print STDERR "\nNumber of lines = " . $#$resultsPTR . "\n";
return (0);
}
main ();
Comments
Post a Comment