On Thu, 2004-05-27 at 11:21, Ramprasad A Padmanabhan wrote:
> On Thu, 2004-05-27 at 15:09, Jose Alves de Castro wrote:
> That was simply neat. I had read in a perl book ' there is always a
> shorter way in perl '. I think this proves it. 
> 
> But to think of it there is one hitch
> 
> suppose my string is 'god'
> 
> Assume
> $word = "good"
> $r = qr/^[god]+$/
> 
> 
> then $r would match $word.  Can you think of a good work around ? 

Oh... you want one of each letter only, is that it? Oh boy...

perl -lne 'BEGIN{for(qw(g o d)){$r{$_}++}}split/
/;for(@_){%a=%r;$a{$_}-- for split//;print unless grep $a{$_},keys %a}'
file

As before, I'm gonna tear this down :-)

=====================
#!/usr/bin/perl -lne
use strict;

BEGIN { for (qw(g o d)) { $r{$_}++} }

split/ /;

for (@_) {
  %a=%r;
  $a{$_}-- for split//;
  print unless grep $a{$_},keys %a
}
=====================

Now I'm going to explain it (or at least try to...)

=====================
#!/usr/bin/perl -lne
# the -l switch chomps the line for you, and when you print, it prints
the \n too (for a better understanding of this, perldoc perlrun and then
search for -l)

use strict;
# I don't use this for one-liners, but always use it for scripts

my %r;
BEGIN { for (qw(g o d)) { $r{$_}++} }
# ok, our BEGIN block now holds how many of each letter we want

split/ /;
# we split the input line in words

my %a
for (@_) { # for each word
  %a = %r; # we note how many of each letter we want
  $a{$_}-- for split//; # and for each letter we have, we note down that
there's one less of that letter we need
  print unless grep $a{$_},keys %a
  # if there is any element in the hash %a with a number different from
0, we don't print it
}
=====================

I hope this is what you wanted :-)

Since this is a beginners list, I'm going to explain this line a bit
further:

$a{$_}-- for split//;

This is the same as:

for (split //) { $a{$_}-- }

Which is the same as:

for (split //, $_) { $a{$_}-- }

Basically, we split the word with an empty regular expression (meaning
we'll get its characters) and for each of those characters we decrement
its corresponding value in %a (even if it doesn't exist, for that
matter).

HTH, :-)

jac

> Thanks
> Ram
> 
-- 
Josà Alves de Castro <[EMAIL PROTECTED]>
Telbit - Tecnologias de InformaÃÃo


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to