# $Id: Tpl.pm,v 1.1 2001/02/26 11:02:37 parf Exp $ # Template processing Library # Author: Parf # package Tpl; =head1 Parfs Template related functions LoadParameters from passed files, ommit comments (#...) to specified hashref =cut $Tpl::dbg=255; # Debug Level # 1 - Saving, 2 - Loading # form1: $hashref, @files -> Load Data into given Hash # form2: @files -> Load Data into empty Hash # Return hashref to param sub LoadPar { my $D={}; $D=shift if ref($_[0]); while(my $par=shift ) { open (F,$par) || next; dbg(2,"Loading Paramerers from: $par "); my ($k,$v); while() { next if /^#/; # skip comments # chop; if ( /^([^\s]*?)=/ ) { $D->{$k}=$v if ($k); ($k,$v)=/^([^\s]*?)=(.*?)$/; } else { $v.=$_; } } 1 while chomp $v; # remove all unneeded \n $D->{$k}=$v if ($k); # Last Key=Value close F; } $D; } # Load File into arrayref # Skip comments sub Load { my @Data; open (F, $_[0] ) || return []; dbg(2,"Load File $_[0]"); while() { next if /^#/; # Skip Comments next if /^$/; # Skip empty lines push @Data,$_; } close F; [@Data] } # Save data to file (any type of data) # $fn, @data_to_save # $fn, [@hash] # $fn, [%hash] sub Save { my ($fn,@dta)=@_; dbg(1,"Saving to: $fn"); my $d; open(F, ">$fn"); for(@dta) { $d=$_; print F @$d if (ref($d) eq 'ARRAY'); if (ref($d) eq 'HASH') { print F "$_=".$d->{$_}."\n" for(keys %$d) ; } print F $d unless(ref($d)); } close F; } # Basic Template processing %xxx% # array ref, hashref return result sub Apply { my ($src,$D)=@_; my $s=''; for (@$src) { s/%(\w+)%/$D->{$1}/ge; # Template Processing $s.=$_; } $s; } sub dbg { # DEBUG my $d=shift; if ($d & $dbg) { chomp, print for(@_); print "\n" ; } } 1;