Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: $dbh could not be passed to function unless another variable is also passed

by hippo (Bishop)
on Aug 08, 2019 at 13:02 UTC ( [id://11104168]=note: print w/replies, xml ) Need Help??


in reply to $dbh could not be passed to function unless another variable is also passed

Your pastebinned code includes this line:

    my $dbh = @_;   # Case #2

This almost certainly doesn't do what you want as it enforces scalar context. Use list context instead:

my ($dbh) = @_; # Case #2

See the Context tutorial for more on this. In future, please include your code in the question (enclosed withing <code> ... </code> tags) rather than a transient off-site link.

Replies are listed 'Best First'.
Re^2: $dbh could not be passed to function unless another variable is also passed
by tukusejssirs (Beadle) on Aug 08, 2019 at 13:14 UTC
    Indeed it works. Thank you. But can you ten me, why my $dbh = $_[0] does not work?

      That also works fine. SSCCE:

      $ cat close.pl #!/usr/bin/env perl use strict; use warnings; use DBI; my $dbh = DBI->connect ('dbi:SQLite:dbname=foo', '', ''); close_db ($dbh); sub close_db { my $dbh = $_[0]; $dbh->disconnect or die "Could not disconnect: $DBI::errstr\n"; } $ perl close.pl $

        Probably I still miss something.

        I have another function called create_table and the db handle does not pass correctly (should I bless it?). I does work when I create the handle within the function.

        create_table($dbh, $table, "record_date char(20)"); sub create_table { use DBI; # Variables my $sth; # Database handle my $dbh = "$_[0]"; # Table name and optionally schema name (schema.table) my $table = "$_[1]"; # Columns and their type my $cols_type = "$_[2]"; # } else { # die RED, "ERROR: You have to supply database handle, table n +ame, the columns list with their type and if you to disconnect the da +tabase connection.\n Stopped$!"; # } # Create table $sth = $dbh->prepare("create table $table ($cols_type);"); $sth->execute(); print "INFO: The table has been created successfully.\n"; return; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11104168]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2024-04-18 16:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found