I'm attempting to pass a database handle to a subroutine. Searches around here return posts that say "It just works." And as I review my code it seems I'm doing the RightThing(tm)
Please point out what I am doing wrong. Update: moritz quickly identified the problem. You probably can too. If you can't spot it right off, then you have a nice little exercise to work.
I've created a small database derived from US Census Gazetteer data. For each county in the US it contains, among other bits, the FIPS ID and latitude/longitude center point. The point of the code is take an arbitrary lat/long coordinate and determine which counties are "nearby". The code in which I set things up:
!/usr/bin/perl use strict; use warnings; use lib 'lib'; use Geo;
use autodie; use DBD::SQLite; use Data::Dumper; use lib 'lib'; use Geo; my $dbh = DBI->connect( "dbi:SQLite:dbname=us_counties.db", "", "", { RaiseError => 1, AutoCommit => 1 }, ); my $states = $dbh->selectall_hashref( "SELECT id, code FROM state", 'i +d' ); my $range = .3; # at US latitudes .3 degree is about 20 miles of sur +face dist while(<DATA>) { chomp; s/"//g; my ($lat,$long) = split /,/; my $range = .3; # at US latitudes .3 degree is about 20 mile +s of surface distance my $county_ref = Geo::find_near_counties( $dbh, $lat, $long, $ +range ); my $print_stuff = defined $county_ref ? scalar @$county_ref : + "None found "; print $print_stuff, " counties found for $lat and $long\n"; } __DATA__ 85,-110 46,-115 27,-81 43,-74 45,-93 48,-104 40,-85
package Geo; sub find_near_counties {
my ( $dbh, $lat, $long, $range ) = @_; my $increment = .3; my @sql_parms = ( $lat - $range, $lat + $range, $long - $rang +e, $long + $range ) ; my $query = "SELECT fips FROM county WHERE latitude > ? AND l +atitude < ? AND longitude > ? AND longitude < ? "; my $county_ref = $dbh->selectcol_arrayref($query, {}, @sql_par +ms ); if( ! scalar @$county_ref ) { if ( $range > 3 ) { return undef; } return find_near_counties( $lat, $long, $range+$increm +ent ); } return $county_ref; } 1;
Though comments on my proto-modularization will be appreciated I'm really here to resolve how to pass the database handle into the sub routine.
So what is my blind spot in passing $dbh?
In reply to Passing $dbh to subroutine - cluestick whack needed by mikeraz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |