# Copyright (c) 2008-2011 bivio Software, Inc. All Rights Reserved. # # Visit http://www.bivio.biz for more info. # # This library is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of the # License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; If not, you may get a copy from: # http://www.opensource.org/licenses/lgpl-license.html # # $Id: Template.pm,v 1.3 2011/02/06 01:48:24 nagler Exp $ package Bivio::IO::Template; use strict; use Bivio::Base 'Bivio::UNIVERSAL'; our($VERSION) = sprintf('%d.%02d', q$Revision: 1.3 $ =~ /\d+/g); my($_F) = b_use('IO.File'); sub replace_in_file { my($proto, $file_name, $vars) = @_; return $proto->replace_in_string($_F->read($file_name), $vars); } sub replace_in_string { my(undef, $template, $vars) = @_; my($d) = ref($template) ? $template : \$template; $$d =~ s{(\$\$)|\$\{([a-z]\w*)\}|\$([a-z]\w*)}{_do($vars, $1, $2, $3)}egs; return ref($template) ? $d : $$d; } sub _do { my($vars) = shift(@_); my($in) = grep(defined($_), @_); return '$' if $in eq '$$'; foreach my $v ($in, '') { next unless exists($vars->{$v}); my($out) = $vars->{$v}; $out = $out->($in) if ref($out) eq 'CODE'; Bivio::Die->die($in, ': var value is undefined') unless defined($out); Bivio::Die->die($in, ': var value is a reference: ', $out) if ref($out); return $out; } Bivio::Die->die($in, ': not found in vars map'); # DOES NOT RETURN } 1;