Okay, just a quick one before I head off to bed. First, grep's points were spot on. Second, I went ahead and recoded this the way I think you were intending it. I grab the players and stick them in an array. I grab the scores and stick them in a hash. Then, I create another hash and use a hash slice (with players as the key) to match listed players with their scores. I tested it on a couple of small data files and it seems to work fine.
#!/usr/bin/perl -w use strict; my $team_file = shift || 'player'; # you can specify a team file on th +e command # line or take the default my $scores = 'score'; # get players open TEAM, "< $team_file" or die "Cannot open $team_file for reading: +$!"; # the grep ensures that we actually have data chomp( my @players = grep /\w+/, <TEAM> ); close TEAM; # get scores open SCORE, "< $scores" or die "Cannot open $scores for reading: $!"; my %all_scores = map {chomp;split/,/} grep { /[^,]+,[^,]+/ } <SCORE>; close SCORE; # get player scores for listed players my %player_scores; @player_scores{ @players } = @all_scores{ @players }; while ( my ( $player, $score ) = each %player_scores ) { print "Player: $player\tScore: $score\n"; }
The caveat here, though, is to understand what I did as opposed to just using it. You can learn a fair amount of stuff that would be beneficial for good programming practices.
Incidentally, you might wonder why I threw that map and grep statement in there. This is because, on the off chance this is homework, I want something that you can't explain to an instructor (no offense). If, on the other hand, you need this for a personal or work problem, then it should work just fine.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
In reply to Re: help with extracting data
by Ovid
in thread help with extracting data
by perlinacan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |