Dealing with SQL Server nvarchar’s and perl

As it was a bugger to track down this solution …

Use Encode;
my $dbh = DBI->connect($db->{'source'},$db->{'user'},$db->{'pass'})
or die "{\"error\": Can't connect to $db->{'source'}: $DBI::errstr}";

my $retval = -1;
my $nvarchar;
my $utfchar;
my $sth;
my $maxlen = 4000;

$sth = $dbh->prepare("{ ? = call GetNVARCHAR ( ? ) }");
$sth->bind_param_inout( 1, \$retval, $maxlen );
$sth->bind_param_inout( 2, \$nvarchar, $maxlen );
$sth->execute();

$utfchar = decode("UCS-2LE", $nvarchar );