Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Perl 'grammar'

by gamache (Friar)
on Jan 08, 2008 at 21:10 UTC ( [id://661178] : note . print w/replies, xml ) Need Help??

in reply to Perl 'grammar'

Here is a Perlish way to convert a name into AD format:
sub format_name_for_AD { my $empl_name = shift; # $empl_name has the form "Last, + First" my ($last, $first) = $empl_name=~/^([^,]+), (.+)/ or return undef; return uc(substr($first, 0, 1)) . ucfirst($last); } for ('Smith, John', 'Wall, Larry', 'Perlis, Alan', 'Ritchie, Dennis') +{ print format_name_for_AD($_), "\n"; }
I'll leave what's going on as an exercise to the reader (hint: perlre), but as a short comment, I'll say that string matching in Perl shouldn't look like string matching in C. :)

Replies are listed 'Best First'.
Re^2: Perl 'grammar'
by WoodyWeaver (Monk) on Jan 08, 2008 at 22:28 UTC
    why is
    my $empl_name = shift; my ($last, $first) = $empl_name=~/^([^,]+), (.+)/ or return undef;
    preferred over
    my ($last, $first) = /(.*), (.*)/ or return undef;
    (or perhaps /(.*),\s*(.*)/ ?)
      Hell, why not sub format_name_for_AD {/(.+), (.)/ ? $2.$1 : undef}?
        Good point. You lose the uc bit, but its awfully tight.

        I think I was reacting more to the parameter unpacking. The sub is handed a compound, and the parameter is stored and then broken apart. I tend to think of that breaking as part of the unpacking process, so in essence get two params passed to the sub in a particular format, hence my "first" line produces those two variables.

        It all comes down to chasing errors, I suppose. I've gotten the habit of putting in a print (or warn) at subroutine entry with the parameters passed controlled by a debug variable. With the one-liner, you can't really do that. But then again, its so bloody simple, perhaps its not necessary.


      The two are not the same. Consider what happens when the sub is called as format_name_for_AD($foo).
        Ah, $_ != $_[0]. I did not think of that.