When data is put into a .txt file, how do you manipulate it and then output it? (If you're wanting to average some items, or add others, etc. once they're entered into the file.)

Dani AI

Generated

A few practical points that tie what wants to do with 's good suggestion to keep each game as one record: use a standard record format (CSV or JSON) or a tiny database (SQLite) instead of a custom delimiter. That avoids parsing mistakes and makes summing/averaging trivial. The general algorithm is simple: read each record, coerce numeric fields, keep running sums and counts, compare the two score fields per record to decide the winner (while still storing both scores for display), then compute averages as sum/count.

Example (Python) — assume a CSV with a header row like week,location,team_score,opp_score,sacks,.... This reads the file, totals sacks, counts games and wins, and prints averages:

import csv
from collections import defaultdict

totals = defaultdict(float)
games = 0
wins = 0

with open('nfl_stats.csv', newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        games += 1
        team = int(row.get('team_score', 0))
        opp = int(row.get('opp_score', 0))
        if team > opp:
            wins += 1
        totals['sacks'] += float(row.get('sacks', 0) or 0)

print('games:', games, 'wins:', wins)
print('avg sacks:', totals['sacks'] / games if games else 0)

Notes and cautions: validate and normalize incoming form values (empty strings => 0), guard against division-by-zero, and include a header row so field order is explicit. If multiple web processes may write at once, use file locking or switch to SQLite (atomic writes and easy aggregates). For per-week incremental updates you can recompute from the whole file (simpler and safer) or maintain a separate aggregates store — but that requires careful locking and update logic.

Further reading: Python CSV module (docs), SQLite (site), Perl CSV tooling (Text::CSV), and Perl flock for file locking (perldoc).

Recommended Answers

All 6 Replies

read the file however you want, get the data you want into variables and use the appropriate operators to do the data munging. Where are you stuck?

Here's what I have so far:

print "Content-type: text/html\n\n";
use CGI qw(:standard);
use strict;

#variable declarations and input assignments
my ($weekNum, $whichWeek, $homeOrAway, $whereAt, $homeCounter, $AwayCounter, $yourTmScore, $otherTmScore, $passYrdPGame, $rushYrdPGame, 
    $sacks, $sacksAllowed, $turnovForcedPerGame, $turnovAllowedPGame, $tds, $tdsAllowed, $passYrdTotal, $passYrdAvg, $rushYrdTotal, 
    $rushYrdAvg, $sacksTotal, $sacksPerGameAvg, $sacksAllowedTotal, $sacksAllowedAvg, $turnovForcedTotal, $turnovForcedAvg,
    $turnovAllowedTotal, $turnovAllowedAvg,$tdsTotal, $tdsAvg, $tdsAllowedTotal, $tdsAllowedAvg, $wins, $losses, $winPercent, 
    $winPercentHome, $winPercentAway);
$whichWeek = param('weekNum');
$whereAt = param('gamePlayed');
$yourTmScore = param('yourTmScore');
$otherTmScore = param('otherTmScore');
$passYrdPGame = param('passYrdPGame');
$rushYrdPGame = param('rushYrdPGame');
$sacks = param('sacks');
$sacksAllowed = param('sacksAllowed');
$turnovForcedPerGame = param('turnovForcedPerGame');
$turnovAllowedPGame = param('turnovAllowedPGame');
$tds = param('tds');
$tdsAllowed = param('tdsAllowed');

#save to file
open(OUTFILE, ">>","nflStats.txt")
	or die "Error opening nflStats.txt $!, stopped";
print OUTFILE "$whichWeek\n";
print OUTFILE "$whereAt\n";
print OUTFILE "$yourTmScore\n";
print OUTFILE "$otherTmScore\n";
print OUTFILE "$passYrdPGame\n";
print OUTFILE "$rushYrdPGame\n";
print OUTFILE "$sacks\n";
print OUTFILE "$sacksAllowed\n";
print OUTFILE "$turnovForcedPerGame\n";
print OUTFILE "$turnovAllowedPGame\n";
print OUTFILE "$tds\n";
print OUTFILE "$tdsAllowed\n";
close(OUTFILE);

#calculate stats
open(INFILE, "<", "nflStats.txt");
@votes = <INFILE>;
close(INFILE);
foreach my $cycle (@votes) {
	$pres_count[$pres] = $pres_count[$pres] + 1;
}

I'm wanting to compare yourTmScore and otherTmScore. Whichever is highest, display it on the generated page. But I also need to display both scores on the generated page.

Then, the $sacks needs to be added to any previously entered data for that variable. A total and avg per game needs to be output on the generated page.

I'm doing a lot of other things, but these are pretty much examples of the two common things being done throughout.

I suggest you use a single line to hold all the data:

#save to file
open(OUTFILE, ">>","nflStats.txt")
	or die "Error opening nflStats.txt $!, stopped";
print OUTFILE join(':::',
                           $whichWeek, $whereAt, $yourTmScore, $otherTmScore,
                           $passYrdPGame, $rushYrdPGame, $sacks, $sacksAllowed, 
                           $turnovForcedPerGame, $turnovAllowedPGame, $tds, $tdsAllowed), "\n";
close(OUTFILE);

Then you open the file and split each line into a list of variables:

#calculate stats
open(INFILE, "<", "nflStats.txt");
while(<INFILE>) {
   my ($whichWeek, $whereAt, $yourTmScore, $otherTmScore,
          $passYrdPGame, $rushYrdPGame, $sacks, $sacksAllowed, 
          $turnovForcedPerGame, $turnovAllowedPGame, $tds, $tdsAllowed) = split(':::');
  ### do whatever you want with each variable now
}
close INFILE;

What are the two sets of

(':::');

for?

Since several of the items need to be added & averaged, how do I go about that. For instance, $passYrdPGame gets entered weekly. How do I add week 1, 2, & 3 together, then average them? Will I need to give it a new name every week or how will I go about it?

What are the two sets of

(':::');

for?

the ':::' is the file delimiter. So your lines might look like this when stored to disk:

1:::3:::4:::23:::7:::12:::55

Later when you read the file you split each line using ':::' and store the individual fields in a list like I already showed you.

How you go about adding/averaging is up to you. You an use sepreate files (for each week) and you would open and read each file and add/average the fields that you want.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.