in reply to printing hashes

Because hashes don't interpolate into quotes. Which is kind of like saying "Because."

No sensible, generally useful hash-to-string conversion was proposed. So there isn't one. Without quotes, it gets turned into a list, and each element is printed.


Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: printing hashes
by TimToady (Parson) on May 07, 2005 at 01:39 UTC
    Perl 6 will interpolate spacetab-separated pairs, one per line, though the restrictions on interpolating arrays and hashes are tightened a bit to avoid accidental interpolation of email addresses and printf formats. You have to do something like:
    say "Array is @array[]"; say "Array is {@array}"; say "Hash is %hash{}"; say "Hash is {%hash}";
    Only scalars interpolate without some kind of bracketing.

    The space-separated form was chosen to make it easy to split on whitespace, but it's expected that most hash interpolations will in fact specify some more explicit format:

    say "Hash is %hash.as('%s => %s', ', ')";

      Looks like pugs does most of this:

      $ pugs -e'my @array=1..5;say "Array is @array[]";' Array is 1 2 3 4 5 $ pugs -e'my @array=1..5;say "Array is {@array}";' Array is 1 2 3 4 5 $ pugs -e'my %hash;%hash{"a".."c"}=1..3;say "Hash is %hash{}"' Hash is a 1 b 2 c 3 $ pugs -e'my %hash;%hash{"a".."c"}=1..3;say "Hash is {%hash}"' Hash is a 1 b 2 c 3 $ pugs -e'my %hash;%hash{"a".."c"}=1..3;say "Hash is %hash.as(q(%s => +%s), q(, ))";' *** Error: No compatible subroutine found: "&as" at -e line 1, column +35-73 $
      Pugs version is 6.2.2.

      After Compline,
      Zaxo

Re^2: printing hashes
by tlm (Prior) on May 06, 2005 at 02:19 UTC

    I'm surprised you didn't propose this variant of your earlier post today:

    use List::Util 'reduce'; my %hash = ( foo => 1, bar => 2, baz => 3 ); my $count = 0; print +( reduce {$a . (++$count % 2 ? ' => ' : ', ') . $b} %hash ), $/; __END__ bar => 2, baz => 3, foo => 1
    ...or any other of the other join alternation schemes.

    the lowliest monk

      In that case, the question was "How do I get the output format I want?" This is a case of "Why doesn't Perl interpolate hashes in strings?" I only shamelessly plug my previous posts when it's justified.

      Of course, with the right syntax, Perl will interpolate anything in a string.

      my %hash = ( foo => 1, bar => 2, baz => 3 ); print "@{[%hash]}";
      But here's another reducing scheme that doesn't involve strenuous exercise or counting calories:
      print((reduce { $a . ($$...$$ ? ' => ' : ',') . $b } %hash), $/);
      The flip-flop doesn't maintain state between calls because in this case, it's not the same flip-flop on each call! Each entry into a subroutine gets a "different" flip-flop.

      Caution: Contents may have been coded under pressure.