On Thu, 19 Dec 2013 12:27:09 -0600, Rick T wrote:

> The following three lines are from a program that works fine for me.
> 
>       # Choose template file
>       use constant TMPL_FILE =>
>       "/big/dom/xoldserver/www/templates/open_courses3.html"; my $tmpl 
= new
>       HTML::Template( filename => TMPL_FILE );
> 
> I wanted to make the program more portable, which means changing the
> name of the server. My idea was to put the following
> 
>       my $server = “newserver”
> 
> at the beginning of the code, then have the later lines of code use this
> string. That way I’d only have to change the one line when moving to
> another server. What I tried first was
> 
>       use constant TMPL_FILE => "/big/dom/x” . $server .
>       “/www/templates/open_courses3.html";
> 
> This gave me a syntax error, as did several variants I tried. I looked
> up “use constant” in Learning Perl but found the discussion over my head
> (I’m a beginner!), so I was hoping someone could explain a correct way
> to write this code if there is one.
> 
> 
> Likewise, I’d like some HTML code I use to be more portable. There, the
> line that refers to a server is in a form action
> 
>       <form action="http://www.oldserver.com/cgi-bin/student_login3.cgi";
>       method="post" name="FormName">
> 
> Again I’d like to declare the server at the top of the code. I realize
> this is not strictly speaking a Perl question, but maybe there is a Perl
> solution?!
> 

You haven't posted enough code to replicate the symptoms, but I'm 
guessing it boils down to:

use strict;
use warnings;

my $server = "newserver";
use constant TMPL_FILE => "/big/dom/x" . $server . 
"/www/templates/open_courses3.html";


print TMPL_FILE, "\n";

Which results in:

% perl foo.pl
Use of uninitialized value $server in concatenation (.) or string at 
foo.pl line 5.
/big/dom/x/www/templates/open_courses3.html


A little bit of knowledge about how Perl parses and compiles code helps 
here.

use statements are run at compile time, not execution time. The

my $server = "newserver";

line is run at execution time, after the use statement is run.  Therefore,
$server isn't defined when the use statement attempts to create a string 
with it.

The easiest way to fix this is to create a new constant and use that:

use constant SERVER => "newserver";
use constant TMPL_FILE => "/big/dom/x" . SERVER . 
"/www/templates/open_courses3.html";

That gives the expected result:

% perl foo.pl
/big/dom/xnewserver/www/templates/open_courses3.html


Diab

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to