in reply to Making a title/headline

You were on the right track.

use strict; my $title = "this and that are the way to go"; $title = make_a_title( $title ); print $title; sub make_a_title { my $title = shift; my @nocapslist = qw( in and the for it but to with about or nor because as that ); my %nocapslist; @nocapslist{ @nocapslist } = undef; my @wordlist = split /\s+/, $title; $wordlist[0] = ucfirst $wordlist[0]; foreach (@wordlist) { $_ = ucfirst if ! exists $nocapslist{ $_ }; } return join ' ', @wordlist; }

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid) Re: Making a title/headline
by Kickstart (Pilgrim) on Dec 15, 2001 at 04:33 UTC
    Very helpful! I'm curious though...what is done with these two lines?

    my %nocapslist; @nocapslist{ @nocapslist } = undef;

    Kickstart

      I declared a hash and then used a hash slice to set all of the keys in the has equal to the values of the array and all of the hash values equal to 'undef'. If you'd like to see it better, you can add these two lines after this code:

      use Data::Dumper; print Dumper \%nocapslist;

      That produces:

      $VAR1 = { 'nor' => undef, 'with' => undef, 'in' => undef, 'or' => undef, 'about' => undef, 'that' => undef, 'as' => undef, 'the' => undef, 'and' => undef, 'for' => undef, 'it' => undef, 'but' => undef, 'to' => undef, 'because' => undef };

      Also, note that we're really not "setting" the values to undef. That's just setting the first hash value to undef and the rest default to that. If you wanted to set all of the values to 1, for example, you'd do something like this:

      @nocapslist{ @nocapslist } = (1) x @nocapslist;

      There are two benefits to using a hash instead of a grep. The first is that the hash lookup is faster. I don't really consider that a benefit, though, because it's always better to optimize for clarity than speed. I changed it to a hash for the second reason: using exists is much easier than using a grep, in terms of programmers understanding it.

      Cheers,
      Ovid

      Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      This uses a hash as hashslice, and so sets the values of the keys contained by @nocapslist to undef. I'd prefer
      @nocapslist{ @nocapslist } = ();
      because in my eyes, undef is a scalar value...

      But it's just a matter of different tastes ;-)

      Best regards,
      perl -e "print a|r,p|d=>b|p=>chr 3**2 .7=>t and t"