#!/usr/bin/perl -w use strict; ############ # INIT # ############ # Hardcoded params -- you'd probably get these from CGI, though my $view = ''; # In what format to view the data my $author = ''; # If viewing by author, which author? ############ # MAIN # ############ # These will be arrayrefs, so it's easier to pass them to subs my $articles = []; my $colOrder = []; # Print the article list, depending on the chosen view if ($view eq "byAuthor") { $colOrder = [qw.title date news.]; $articles = &get_articles_by_author($author); } else { # Default view $colOrder = [qw.title date author news.]; $articles = &get_articles(); } &print_articles($articles, $colOrder); ############ # SUBS # ############ ### Grabs all of the articles out of a data file and returns them as an ### array of hashrefs. This is the only sub you'll use to get the data. If ### later you decide to put the articles in a db, you only have to change this ### one sub. sub get_articles { # Grab each line in reverse order open (NEWS, "; close(NEWS); # Your column names, in the order they appear in the file my @colNames = qw(time_stamp title date author news avatar); # Store the contents of the file in a table (array of hashrefs) my @table = (); foreach my $article (@articles) { chomp $article; my @vals = split /\|/, $article; # Assign each value to its column name, in a hash my %row = (); foreach my $col (@colNames) { $row{$col} = shift @vals; } # Add this row to the table, as a hashref push @table, \%row; } return \@table; } ### Get the list of articles by a single author, by getting the full list of ### articles from the file, and then filtering out everything but the given author. sub get_articles_by_author { my $author = shift || die "need an author"; my $articles = &get_articles(); # Build a list of articles by the given author my @artByAuth = (); foreach my $article (@$articles) { if ($article->{'author'} eq $author) { push @artByAuth, $article; } } return \@artByAuth; } ### Prints a given list of articles. ### Optional param: the order of columns to display. sub print_articles { my $articles = shift || die "Need an article list"; my $colOrder = shift || keys %{ $articles->[0] }; # Above, if no $colOrder was given, use all of the cols in the table. # Just get the keys in the hash for the first article. # Print the articles print "Content-type:text/html\n\n"; print qq~~; foreach my $article (@$articles) { foreach my $col (@$colOrder) { print qq~ ~; } } print "
$article->{$col}

\n"; }