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


in reply to Evaling Strings in Subs for Hashref Variable Names to Values

If you use next, there is no need to use else: the code after next can only be reached if the condition was not true.

You do not want to use eval BLOCK to catch exceptions. You want to use eval STRING to evaluate a constructed code. You should include the assignment in the code, though:

#!/usr/bin/perl use warnings; use strict; my $sql_var_hr; $sql_var_hr->{col_name} = 'column_name'; my $sql = get_sql($sql_var_hr); sub get_sql { my ($vars) = @_; my $sql; while (my $iline = <DATA>) { next if $iline =~ /^#/; $sql .= $iline; } print "pre_eval: $sql\n"; eval '$sql = "' . $sql . '"' or warn $@; print "post_eval: $sql\n"; return $sql; } __DATA__ select $vars->{col_name} from schema.table select $$vars{col_name} from schema.table
Using "templates" might solve lots of problems this naïve approach might cause.
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Evaling Strings in Subs for Hashref Variable Names to Values
by theleftsock (Beadle) on Nov 12, 2012 at 17:25 UTC

    Thanks for the response. I didn't think of evaling the assignment, that's what I missed. I had tried the string eval previously, but not the assignment. I did have strict and warnings in my original code, but dropped it to post a simple example.

    A templating system is a good idea, maybe break the SQL down into segments? Yea, it would be pretty easy to make mistakes, and hard to figure out what the var names are supposed to be. Hopefully in the beta implement of this I can solve some of those issues. Any recommendations on a templating system or process that is already established? I guess I could use some kind of markup....

    either way, thanks for the response! It's really helpful.

    -theleftsock
      I think SQL::Template might help you here. The SQL code is decoupled from your Perl-script and resides in an XML-file. The variable data is provided through a hash-reference.

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      My blog: Imperial Deltronics

        From a cursory readthrough, it looks like SQL::Template is very similar to what I am doing, only it has some markup with it. Might be more extensible, or it might be a good way to combine all my SQL into a single file for use.

        thanks -theleftsock