package TripodInsert; ################### # TripodInsert.pm # ############################################################################## # TripodInsert is a module to make it easier for you to include dynamic # # inserts into your pages. It's very similar to TripodPage, and you should # # read the comments for TripodPage before using this module - the comments # # here will refer to it repeatedly. # # # # There's only one function you should need to use in TripodInsert, and # # that's fetchInsert(). fetchInsert() takes a text file, looks for # # variables, fills in the variables with the contents of a variable hash, # # and returns the result. This is very similar to how sendPage() from # # TripodPage works - indeed, fetchInsert() essentially is sendPage(), except # # that instead of sending its output to the web server along with an HTTP # # header, it returns the filled-in template as a value to your script. From # # there, you can do whatever you want with it - print it out, combine it # # with other templates into a larger page, save it as a file, etc. Here's # # an example: # # # # $template_file = 'log_template.txt'; # # $variable_hash{timezone} = $ENV{TZ}; # # $variable_hash{ip_address} = $ENV{REMOTE_HOST}; # # $variable_hash{browser} = $ENV{HTTP_USER_AGENT}; # # $log_line = $INSERT->fetchInsert($template_file); # # open (LOG, '>> my_log.txt'); # # print LOG $log_line; # # close LOG; # # # # The 'log_template.txt' that goes with the script looks like this: # # # # ----------------------------- # # Timezone: $timezone # # IP: $ip_address # # Browser: $browser # # ----------------------------- # # # # This example works like the example given for sendPage(), except that here # # each visitor's timezone, ip address, and browser are added to a log file # # named 'my_log.txt', rather than being outputted as a web page. # ############################################################################## sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } # fills an insert either from a string_ref or a file sub fetchInsert { my($self,$string_ref_or_file,$hash_ref) = @_; if (ref $string_ref_or_file) { $$string_ref_or_file =~ s|\$(\w+)|returnValueOrKey($1,$hash_ref)|eg; } else { return $self->fetchFileInsert($string_ref_or_file,$hash_ref); } } # For error messages and other insertions. sub fetchFileInsert { my($self,$insert_file,$hash_ref) = @_; my($file,$old_eol,$message); $old_eol = $/; undef $/; # Return an empty insert if we can't open the file. open(IF,"< $insert_file") or return ''; $message = ; close IF; $/ = $old_eol; # Interpolate variables into the message. $message =~ s|\$(\w+)|returnValueOrKey($1,$hash_ref)|eg; return $message; } sub returnValueOrKey { ($key,$hash_ref) = @_; if (defined($$hash_ref{$key})) { return $$hash_ref{$key}; } else { return '$' . $key; } } 1;