in reply to Text Tagging

#! /usr/bin/perl use strict; use warnings; my $t = Tags->new( { txt_file => q{text.txt}, tag_files => [qw{tag1.txt tag2.txt}], } ); my $count = 3; for (0..$count){ print $t->output; } package Tags; sub new { my $class = shift; my $args = shift; my $self = {}; die q{no txt file} unless exists $args->{txt_file}; die q{no tag files} unless exists $args->{tag_files}; my $txt_file = $args->{txt_file}; open my $fh, q{<}, $txt_file or die qq{cant open *$txt_file* to read: $!}; $self->{txt} = do{local $\;<$fh>}; my @files = @{$args->{tag_files}}; die q{no tag files} unless @files; for my $file (@files){ open my $fh, q{<}, $file or die qq{cant open *$file* to read: $!}; my @lines = <$fh>; chomp @lines; my ($tag_name) = $file =~ /([^.]+)\./; $self->{$tag_name} = \@lines; } bless $self, $class; return $self; } sub output { my $self = shift; my $txt = $self->{txt}; $txt =~ s/{{([^}]+)}}/$self->next({tag => $1})/eg; return $txt; } sub next { my $self = shift; my $args = shift; my $tag = $args->{tag}; die q{bad tag} unless exists $self->{$tag}; my $tag_txt = shift @{$self->{$tag}}; push @{$self->{$tag}}, $tag_txt; return $tag_txt; }

Lorem ipsum tag1example1 sit amet, consectetur adipiscing elit. Vestibulum bibendum mi in ipsum tag2example1 id sagittis dolor ultrices. Maecenas vitae nunc diam, quis gravida augue. Integer...

Lorem ipsum tag1example2 sit amet, consectetur adipiscing elit. Vestibulum bibendum mi in ipsum tag2example2 id sagittis dolor ultrices. Maecenas vitae nunc diam, quis gravida augue. Integer...

Lorem ipsum tag1example1 sit amet, consectetur adipiscing elit. Vestibulum bibendum mi in ipsum tag2example3 id sagittis dolor ultrices. Maecenas vitae nunc diam, quis gravida augue. Integer...

Lorem ipsum tag1example2 sit amet, consectetur adipiscing elit. Vestibulum bibendum mi in ipsum tag2example1 id sagittis dolor ultrices. Maecenas vitae nunc diam, quis gravida augue. Integer...

--------------------------

If this is homework and you haven't covered oo yet you may have some explaining to do. :-)

The best? Unlikely. Efficient? Depends. I found it easy to write and, in imo, it reads well so I'll find it easier to maintain. It would also be reasonably easy to extend.

update: In some quarters passing arguments around as hashrefs is considered bad for your health - so be prepared. :-)

Replies are listed 'Best First'.
Re^2: Text Tagging
by anlamarama (Acolyte) on Oct 25, 2009 at 07:02 UTC

    Wow, I can't tell you how much I appreciate that.

    No it is not my homework, it's a part of a project. I have been coding in Perl for some time, but have not done anything like this before. So, I could not find a good way to code this, your one is far better than my one.

    Thanks a lot indeed..