Skip to content

Instantly share code, notes, and snippets.

@MattOates
Last active August 26, 2015 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattOates/7678c1d87ff71062a3af to your computer and use it in GitHub Desktop.
Save MattOates/7678c1d87ff71062a3af to your computer and use it in GitHub Desktop.
Boring script to split on some fields from a reddit post https://www.reddit.com/r/perl/comments/3ih6ha/commissioned_work/
#!/usr/bin/env perl
#Write sane perl
use strict;
use warnings;
use feature 'say';
#Use some modules which are sufficiently round wheels
use Text::CSV;
use Getopt::Long;
#The different fields in the file
my ($search_year, $search_name, $search_time, $search_state);
#Get the command line options for the search
GetOptions ('year=i' => \$search_year, 'name=s' => \$search_name, 'time=s' => \$search_time, 'state=s' => \$search_state);
#Just assume one file left on the end for now but you could extend this to give summaries for multiple files
my ($file) = @ARGV;
#How many records matched the arguments, start out with none
my $num_records = 0;
#Use someone elses code to deal with CSV of all kinds
my $csv = Text::CSV->new ({ binary => 1, eol => $/ });
#Open the file that was passed in from the command line
open my $io, "<", $file or die "$file: $!";
#For each row of the CSV grab it from file one at a time while there are some to grab
while (my $row = $csv->getline ($io)) {
#Name the fields so the code is easy to read
my ($year,$name,$time,$state) = @$row;
#Check if any of the fields matched the ones passed in on the command line (if they were) and skip counting the row if not matching
next if (defined $search_year and $year !~ /$search_year/);
next if (defined $search_name and $name !~ /$search_name/);
next if (defined $search_time and $time !~ /$search_time/);
next if (defined $search_state and $state !~ /$search_state/);
#We must have matched everything so can count that as a matched record
$num_records++;
}
#After we counted all the matching records just print that number out
say $num_records;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment