http://www.perlmonks.org?node_id=11108335

LorenzoLu has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm going to modify a perl script which opens a write connection to a Postgresql DB, in this way:

open(DATA_FILE,"<:utf8",$filename) || die print "can not open reading +file --> \"$filename\""; open DB, '| /opt/postgresql-9.4/bin/psql -h ... (here all the paramete +rs)' print DB "copy $table($header) from STDIN CSV;\n"; while ( my $line = <DATA_FILE>) { print DB "$line"; }

Well, I need to configure the DB connection encoding as UTF8, and I already did it successfully for the above open DATA_FILE, but now I'm wondering how to specify the ":utf8" in the "open DB...".

I tried the following one:

open(DB, ">:utf8", '| /opt/postgresql-9.4/bin/psql -h ... ')

but it does not work.

Then I tried:

open(DB, "+>:utf8", '| /opt/postgresql-9.4/bin/psql -h ... ')

still not working.

Any help?

I suppose it fails because of that EXPR parameter ('| /opt/...') which contains a pipe and it is not exactly an expression...

Best,
Lorenzo

Update: 5 Nov 19, footpad: Added HTML formatting tags, per Consideration.

Replies are listed 'Best First'.
Re: PostgreSQL connection set in UTF8
by choroba (Archbishop) on Nov 05, 2019 at 17:05 UTC
    Your code doesn't open a connection to Postgres, it opens a pipe to the postgres client psql. You might try adding the encoding layer to the pipe by specifying
    open my $db, '|-:encoding(UTF-8)', '/opt/postgresql-9.4/bin/psql -h' o +r die $!;

    but switching to DBI and DBD::Pg seems like a much better approach.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re: PostgreSQL connection set in UTF8
by jcb (Vicar) on Nov 06, 2019 at 00:58 UTC

    Try binmode: binmode DB, ':utf8';

    But you should probably be using Text::CSV (or DBD::CSV) and DBI for this, instead of opening a pipe to psql. What happens if a row fails to insert due to a constraint violation in your current code? DBI will report the error.