| 1 | #============================================================= -*-Perl-*- | ||
| 2 | # | ||
| 3 | # Template::Plugin::Datafile | ||
| 4 | # | ||
| 5 | # DESCRIPTION | ||
| 6 | # Template Toolkit Plugin which reads a datafile and constructs a | ||
| 7 | # list object containing hashes representing records in the file. | ||
| 8 | # | ||
| 9 | # AUTHOR | ||
| 10 | # Andy Wardley <abw@wardley.org> | ||
| 11 | # | ||
| 12 | # COPYRIGHT | ||
| 13 | # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. | ||
| 14 | # | ||
| 15 | # This module is free software; you can redistribute it and/or | ||
| 16 | # modify it under the same terms as Perl itself. | ||
| 17 | # | ||
| 18 | #============================================================================ | ||
| 19 | |||
| 20 | package Template::Plugin::Datafile; | ||
| 21 | |||
| 22 | use strict; | ||
| 23 | use warnings; | ||
| 24 | use base 'Template::Plugin'; | ||
| 25 | |||
| 26 | our $VERSION = '3.105'; | ||
| 27 | |||
| 28 | sub new { | ||
| 29 | my ($class, $context, $filename, $params) = @_; | ||
| 30 | my ($delim, $encoding, $line, @fields, @data, @results); | ||
| 31 | my $self = [ ]; | ||
| 32 | local *FD; | ||
| 33 | local $/ = "\n"; | ||
| 34 | |||
| 35 | $params ||= { }; | ||
| 36 | $delim = $params->{'delim'} || ':'; | ||
| 37 | $delim = quotemeta($delim); | ||
| 38 | $encoding = defined $params->{'encoding'} ? ':encoding('.$params->{'encoding'}.')' : ''; | ||
| 39 | |||
| 40 | return $class->error("No filename specified") | ||
| 41 | unless $filename; | ||
| 42 | |||
| 43 | open(FD, '<'.$encoding, $filename) | ||
| 44 | || return $class->error("$filename: $!"); | ||
| 45 | |||
| 46 | # first line of file should contain field definitions | ||
| 47 | while (! $line || $line =~ /^#/) { | ||
| 48 | $line = <FD>; | ||
| 49 | last unless defined $line; | ||
| 50 | chomp $line; | ||
| 51 | $line =~ s/\r$//; | ||
| 52 | } | ||
| 53 | |||
| 54 | return $class->error("first line of file must contain field names") | ||
| 55 | unless defined $line; | ||
| 56 | |||
| 57 | (@fields = split(/\s*$delim\s*/, $line)) | ||
| 58 | || return $class->error("first line of file must contain field names"); | ||
| 59 | |||
| 60 | # read each line of the file | ||
| 61 | while (<FD>) { | ||
| 62 | chomp; | ||
| 63 | s/\r$//; | ||
| 64 | |||
| 65 | # ignore comments and blank lines | ||
| 66 | next if /^#/ || /^\s*$/; | ||
| 67 | |||
| 68 | # split line into fields | ||
| 69 | @data = split(/\s*$delim\s*/); | ||
| 70 | |||
| 71 | # create hash record to represent data | ||
| 72 | my %record; | ||
| 73 | @record{ @fields } = @data; | ||
| 74 | |||
| 75 | push(@$self, \%record); | ||
| 76 | } | ||
| 77 | |||
| 78 | # return $self; | ||
| 79 | bless $self, $class; | ||
| 80 | } | ||
| 81 | |||
| 82 | |||
| 83 | sub as_list { | ||
| 84 | return $_[0]; | ||
| 85 | } | ||
| 86 | |||
| 87 | |||
| 88 | 1; | ||
| 89 | |||
| 90 | __END__ |