Loading ...
Sorry, an error occurred while loading the content.

26471Re: [PBML] Quoting hash keys changes things sometimes

Expand Messages
  • Jenda Krynicky
    Nov 15, 2008
    • 0 Attachment
      From: "Kelly Jones" <kelly.terry.jones@...>
      > Consider:
      > perl -le '$hash{"foo-bar"} = 1; print $hash{foo-bar}'
      > [no result]
      > perl -le '$hash{"foobar"} = 1; print $hash{foobar}'
      > 1
      > I sort of understand this: in the first script, Perl treats foo-bar as
      > a subtraction, and sets $hash{0} to 1. In the second one it assumes
      > you just left off some quotes.

      The rule for automatic quoting within $hash{...} is "if it looks like
      word, it doesn't have to be quoted". And - is not in the list of word
      characters as far as Perl is concerned.

      > My question: since Perl doesn't have constants, what exactly IS
      > foo-bar? Why is it 0?
      > The behavior above seems inconsistent to me. Is it considered a bug?

      No. It's documented behaviour.

      For historical purposed, if you do not "use strict" then

      $var = foo;

      will be treated as

      $var = 'foo';

      if there is no subroutine named foo. It's called "bareword" and was a
      bad idea in my opinion. In your case you are subtracting two strings,
      'foo' and 'bar' which means both are evaluated to a number (zero) and
      then the zeroes are subtracted.

      print('foo' - 'bar');

      This can cause hard to find errors (if for example you mistype a
      subroutine name) so you should always start your scripts with

      use strict;

      which will prevent this.

      ===== Jenda@... === http://Jenda.Krynicky.cz =====
      When it comes to wine, women and song, wizards are allowed
      to get drunk and croon as much as they like.
      -- Terry Pratchett in Sourcery
    • Show all 3 messages in this topic