in reply to Re: DBI and JSON fields
in thread DBI and JSON fields

Note that $. is a special variable in Perl and double quotes expand variables

How silly do I feel now 😕

Thank you for pointing out what should have been obvious to me but clearly wasn't!

Replies are listed 'Best First'.
Re^3: DBI and JSON fields
by stevieb (Canon) on Mar 13, 2024 at 07:37 UTC

    Meh, easy mistake to make.

    Instead of using the concat operator (ie. '.'), you can escape the dollar (note: the single quotes on your href keys are superfluous here):

    "\$.$row->{name}"

    ...or to be even more safe, you can use a special trick to interpolate a variable inside of a string, if it gets more complex. This way, perl knows where the variable is, and the other chars are:

    my $x = 'sent'; print "\$.${x}ence"; # output: $.sentence

    With a hashref, this looks a lot different and is a lot more convoluted*:

    "\$.${\$row->{name}}ence"

    In cases like that, I much prefer sprintf(). It's always a dead reliable way to concoct strings:

    sprintf("\%.%s", $row->{name});

    That way, you can even do things like this:

    my $row = {name => 'sent'}; my $thing = sprintf("\$.%sence", $row->{name}); # output: $.sentence

    For readability, I like to write my db queries so that they're broken down logically, like this:

    my $something_query = qq{ SELECT COUNT(*) FROM Person WHERE Account_idAccount = ? AND JSON_EXISTS(custom, ?) };

    Then, if the variables I need to feed into the engine are anything but single scalars in a list:

    my @array = $dbh->selectrow_array( $something_query, undef, $account, sprintf( "\$.%s", $row->{name} ) );

    There's no reason to feel silly for little things like this. Even the most experienced programmers bang their heads against their desks from time-to-time for seemingly simple issues. The good thing is you were humble enough to reach out, and that led to a successful conclusion. Keep doing that. Future users of your software will appreciate your willingness to ask others for help when you can't quite solve something. Much better to be humble than it is to try to broom the cockroach under the carpet. This quality will lead to your users trusting you. Trust me.

    *- Because you have to reference a reference to a dereferenced reference (...and I still don't think I understand that correctly ;) )
      With a hashref, this looks a lot different and is a lot more convoluted*:
      "\$.${\$row->{name}}ence"
      Uh, no. The ref/def thing is unnecessary, since the hash deref syntax alone will tell the parser where to break:
      pdl> $row->{name} = 'sent' pdl> p "\$.${\$row->{name}}ence" $.sentence pdl> p "\$.$row->{name}ence" $.sentence