diff options
| -rw-r--r-- | challenge-004/andrezgz/perl5/ch-1.pl | 12 | ||||
| -rw-r--r-- | challenge-004/andrezgz/perl5/ch-2.pl | 40 |
2 files changed, 52 insertions, 0 deletions
diff --git a/challenge-004/andrezgz/perl5/ch-1.pl b/challenge-004/andrezgz/perl5/ch-1.pl new file mode 100644 index 0000000000..f18c3fc9f5 --- /dev/null +++ b/challenge-004/andrezgz/perl5/ch-1.pl @@ -0,0 +1,12 @@ +#!/usr/bin/perl + +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-004/ +# Challenge #1 +# Write a script to output the same number of PI digits as the size of your script. +# Say, if your script size is 10, it should print 3.141592653. + +use strict; +use warnings; + +use Math::BigFloat qw/bpi/; +print bpi(-s $0); diff --git a/challenge-004/andrezgz/perl5/ch-2.pl b/challenge-004/andrezgz/perl5/ch-2.pl new file mode 100644 index 0000000000..47cbb7d32d --- /dev/null +++ b/challenge-004/andrezgz/perl5/ch-2.pl @@ -0,0 +1,40 @@ +#!/usr/bin/perl + +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-004/ +# Challenge #2 +# You are given a file containing a list of words (case insensitive 1 word per line) and a list of letters. +# Print each word from the file than can be made using only letters from the list. +# You can use each letter only once (though there can be duplicates and you can use each of them once), +# you don’t have to use all the letters. + +use strict; +use warnings; + +die "Usage: ch-2.pl <words_file> <letters_list>" if scalar(@ARGV) < 2; + +my $words_file = $ARGV[0]; +my $letters_list = $ARGV[1]; + +#Make a hash with available letters and quantity +my %letters; +for my $l (split /,/,$letters_list ){ + $letters{ lc($l) }++; +} + +open(my $fh, "<", $words_file) or die "Could not open words file '$words_file': $!"; + +while( my $word = <$fh> ) { + chomp $word; #remove new line trailing string + print $word.$/ if is_word_printable( lc $word , %letters ); +} +close $fh; + +#Return 1 if $word is composed by letters on the hashed list %letters +sub is_word_printable { + my ( $word, %letters ) = @_; + foreach my $l (split //,$word ){ + return 0 unless (exists $letters{ $l } && $letters{ $l } > 0); + $letters{ $l }--; + } + return 1; +}
\ No newline at end of file |
