#!/usr/local/bin/perl

# COMS3101 Perl Fall 2013
# HW2
# pn_norm.pl

# Read input file
open(IN,$ARGV[0]);
@lines = <IN>;
chomp @lines;
close(IN);

# Output file
open(OUT,">test2n.txt");

# For illustration
$story = join(",",@lines);

# Match parentheses, correct # of digits and hyphen
@phones = $story =~ /\d{3}[ -]*\d{3}[\s-]*\d{4}/g;   
@phones2 = $story =~ /\(\d{3}\)[ -]\d{3}[\s-]\d{4}/g;

# Standard format
# Add ()
(s/(\d{3})/(\1)/) foreach @phones;
push(@phones,@phones2);
foreach (@phones) {
   s/-/ /g;             # remove hyphen
   if ($_ =~ /\)\d/) {  # add space
     substr($_,5,0,' ');
     substr($_,9,0,' ');
   }
}
  
# Report
$np = scalar(@phones);
print "The passage contains $np phone number mentions.\n";
# output file with normalized numbers ‘test2n.txt’ created
print OUT join("\n",@phones);
close(OUT);