package Base::Nifty; use strict; use warnings; use base 'Exporter'; our @EXPORT_OK = qw(get_hash commify grammatical_list line article_sort name_sort my_sort); #get_hash does just that for me, it gets me a hash from a text file, usually a .csv, which I can then use whereever. #written with rindolf in #perlcafe on freenode; golfed with the help of [GrandFather] of PerlMonks. sub get_hash { my ($hash,$data_hash) = @_; open(my $fh, $data_hash->{csv}) or die("can't open $data_hash $!"); while (my $value = <$fh>) { chomp $value; my @inner_array = split(/\|/,$value); my $n = 0; for my $heading (@{$data_hash->{headings}}) { $$hash{$inner_array[0]}{$heading} = $inner_array[$n]; ++$n; } } } #commify was found in the perldocs to put commas in numbers. sub commify { local $_ = shift; 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; return $_; } #grammatical_list is used when I want to print a list with grammatical correctness. #written with the help of DrForr in #perlcafe on freenode, golfed by in #perlmonks on SlashNET. sub grammatical_list { my $conj = shift(@_) . ' '; return @_ if @_ <= 1; return join( ' '.$conj, @_ ) if @_ == 2; my $punc = grep( /,/, @_ ) ? '; ' : ', '; push @_, $conj.pop; join $punc, @_ } #tab and line are just to add tabs and newlines on the output. sub tab { my ($tab) = @_; return ("\t") x $tab; } sub line { my ($tab,$line) = @_; print tab($tab)."$line\n"; } #written mostly by kent/n in #perl on freenode. sub article_sort { my ($c,$d) = @_; for ($c,$d) { $_ =~ s{\s*\b(A|a|An|an|The|the)(_|\s)}{}xi; } return $c cmp $d; } sub name_sort { my ($c,$d,$sort_numer) = @_; return (split /_/, $c)[$sort_numer] cmp (split /_/, $d)[$sort_numer]; } #golfed by [ikegami] on PerlMonks. sub my_sort { my ($c,$d,$type,$sort_number) = @_; my $initial = $c =~ /^index/ ? 0 : 1 <=> $d =~ /^index/ ? 0 : 1 || $c =~ /^ssi/ ? 0 : 1 <=> $d =~ /^ssi/ ? 0 : 1 || $c =~ /css$/ ? 0 : 1 <=> $d =~ /css$/ ? 0 : 1; return $initial if $initial; if ($type eq 'file') { s{\s*\b(?:an?|the)_}{}xi for $c, $d; return $c cmp $d; } elsif ($type eq 'name') { return (split /_/, $c)[$sort_number] cmp (split /_/, $d)[$sort_number]; } else { die("Bad type $type"); } } 1;