简体   繁体   中英

Syntax error using Perl DBI module

I am writing Perl code and using the DBI module in the file with extension .pm .

When importing the DBI module, I am getting an error like

syntax error at /etc/perl/Foo.pm line 13, near "DBI:"
Compilation failed in require at join.pl

In the join.pl file we are calling the module Foo.pm as

use Foo;
Foo::dbconnect();

and the code in Foo.pm is like this

#!/usr/bin/perl

package Foo;

use DBI;

sub dbconnect {
  my $database = "DB_NAME";
  my $user ="user_name";
  my $password = "password";
  my $dsn = "dbi:mysql:$database:localhost:3306";
  my $connect = DBI:connect->($dsn, $user, $password)
      or die "can't connect to the db   $DBI::errstr\n";
  return $connect;
}

1;

I am getting the error in the line

my $connect = DBI:connect->($dsn, $user, $password)
    or die "can't connect to the db   $DBI::errstr\n";

Please help me to solve this issue.

Welcome to SO.

First of all, you should always use strict and use warnings to help find problems in your code.

There's a syntax error in your connect line. Try this:

my $connect = DBI->connect($dsn, $user, $password) 
    or die "can't connect to the db $DBI::errstr\n";

A word of advice: It's a good idea to name your variables after what they represent. I'd suggest $dbh for database handle instead of $connect , but it's up to preference of course.

The syntax you are using for the connect method DBI:connect->(...) is wrong.

It would be valid syntax if you used two colons instead of one and removed the arrow but it still wouldn't work.

What you need is a class method call, like this

my $connect = DBI->connect($dsn, $user, $password)
    or die "can't connect to the db: $DBI::errstr\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM