On Mon, Apr 23, 2001 at 01:15:13PM -0400, David Gilden wrote:

[ brought back to the list with permission ]

> my camel learning perl book has hashs with the key in quotes,
> whats going on with this?

In the early days this was necessary, otherwise the key would be
interpreted as a function and its result used as the key.  I don't think
this has been necessary since perl 5.005,  But, be careful if your key
actually has the same name a function.  Things can get confusing.  For
you if not for perl itself.

The camel's getting pretty long in the tooth now.

> And is there a short hand for the following?
> 
> 
> &checkPrice($in{price});

I was going to mention this before, but I forgot.  Calling a sub as
&sub() is so ...... perl4.  Of course it's still supported and correct,
but I find it helpful to remove superfluous punctuation.  I think it
helps to make the meat of the program stand out.

> sub checkPrice{
> return ($_[0] =~ /^\$?(\d+|\d*\.\d\d)$/) ? 1 : 0;
> }
> 
> # can this be rewritten as:
> sub checkPrice{
> return ( /^\$?(\d+|\d*\.\d\d)$/) ? 1 : 0;
> }

No.  $_ isn't set on entry to a sub - @_ is.  So you will need the first
version, but there is no need for the ?: operator.

    sub checkPrice { return $_[0] =~ /^\$?(\d+|\d*\.\d\d)$/ }

Be careful when manipulating @_ though.  Perl uses pass-by-reference, so
changing @_ changes the actual arguments passed to the sub.  This is why
many subs start off with

  my ($a1, $a2, $a3) = @_

or something similar.  This takes copies of the arguments and
effectively gets you pass-by-value semantics.

Depending on how defensive you are being, you might want to check that
you are being passed one and only one parameter, possibly by using a
prototype or checking the length of @_.

Also, for a function this size I would personally also get rid of the
return keyword.  All subs return the value of their last expression when
they fall off the end, and so I would use

    sub checkPrice { $_[0] =~ /^\$?(\d+|\d*\.\d\d)$/ }

but I know some people are (violently) against this sort of thing.  I
like using Perl's idioms, and with something this size I think it's
pretty obvious what's happening.

For another can of worms, I would also go with check_price() as the name
of the sub.  See perldoc perlstyle.  But this is very personal.  The
convention where I work is checkPrice() and I don't like it, but I'm
learning to live with it.  Almost :-)

-- 
Paul Johnson - [EMAIL PROTECTED]
http://www.pjcj.net

Reply via email to