package PhoneNumber; # Simple class to store various bits of a phone number and roll # them out as a string when needed. use strict; use Carp; my @Valid_Parms = qw( num idd cc ext ); my $Ppat = join('|', @Valid_Parms); sub new { my $class = shift; my %parms = @_; foreach (keys %parms) { croak "Invalid parameter '$_' passed.\n" unless /^$Ppat$/o; } my $self =\%parms; $self->{ext} ||= []; $self->{_native_cc} = 1; bless $self, $class; } sub number { my $self = shift; if (@_) { $self->{num} = shift; delete $self->{_chunked}; } $self->{num}; } sub idd { my $self = shift; @_ ? $self->{idd} = shift : $self->{idd}; } sub _native_cc { # hack for scrambling original dataset my $self = shift; @_ ? $self->{native_cc} = shift : $self->{native_cc}; } sub country_code { my $self = shift; @_ ? $self->{cc} = shift : $self->{cc}; } sub extensions { my $self = shift; if (@_) { @{$self->{ext}} = @_; } @{$self->{ext}}; } sub chunked_number { # Regurgitate a phone number with a 4 digit grouping last, # preceded by 3 digit groups prior to that. my $self = shift; my $num = $self->number; return unless defined $num; if (!$self->{_chunked}) { # Optimize for chunking $num = reverse $num; my @tphn; if ($num =~ s/^(\d{1,4})//) { push(@tphn, $1); } push(@tphn, $num =~ /(\d{1,3})/g); # Undo reversals grep($_ = reverse, @tphn); @tphn = reverse @tphn; # Cache $self->{_chunked} = \@tphn; } @{$self->{_chunked}}; } sub as_string { # Attempt some nice formatting my $self = shift; my $str; my $icode = $self->country_code; $str = "+$icode " if $icode; $str .= join(' ', $self->chunked_number); my @exts = $self->extensions; $str .= (' x ' . join('/', @exts)) if @exts; $str; } 1;