[32376] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 3643 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sun Mar 18 21:09:26 2012

Date: Sun, 18 Mar 2012 18:09:08 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Sun, 18 Mar 2012     Volume: 11 Number: 3643

Today's topics:
    Re: $var = do { ... }? (Tim McDaniel)
    Re: $var = do { ... }? <ben@morrow.me.uk>
    Re: $var = do { ... }? <rweikusat@mssgmbh.com>
        Embedding code in qq{}? <XeCycle@Gmail.com>
    Re: Embedding code in qq{}? <uri@stemsystems.com>
    Re: Embedding code in qq{}? <XeCycle@Gmail.com>
    Re: Embedding code in qq{}? (Tim McDaniel)
    Re: Embedding code in qq{}? <ben@morrow.me.uk>
    Re: Embedding code in qq{}? <uri@stemsystems.com>
    Re: Embedding code in qq{}? (Tim McDaniel)
    Re: Embedding code in qq{}? (Tim McDaniel)
    Re: Embedding code in qq{}? (Randal L. Schwartz)
    Re: Embedding code in qq{}? <uri@stemsystems.com>
    Re: Embedding code in qq{}? <uri@stemsystems.com>
    Re: Embedding code in qq{}? <ben@morrow.me.uk>
    Re: getting hash reference from a package <rweikusat@mssgmbh.com>
    Re: Increment with '#' and decrement with 'b' <news@lawshouse.org>
    Re: Increment with '#' and decrement with 'b' <rweikusat@mssgmbh.com>
    Re: Increment with '#' and decrement with 'b' <oneingray@gmail.com>
    Re: Increment with '#' and decrement with 'b' <news@lawshouse.org>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Sat, 17 Mar 2012 18:48:41 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: $var = do { ... }?
Message-Id: <jk2ma9$5ds$1@reader1.panix.com>

Concerning
    my $result = eval {
        $_ % 2 == 0     and return "even";
        $_ % 3 == 0     and return "divisible by three";
        return "just wrong";
    };

In article <41tc39-jv12.ln1@anubis.morrow.me.uk>,
Ben Morrow  <ben@morrow.me.uk> wrote:
>Quoth tmcd@panix.com:
>> In fact, the eval version is the one that needs the testing, not
>> the sub.  eval traps fatal terminations, and just about anything
>> can die().  In this simple case, I think you'd need
>> "use warnings FATAL => 'numeric';"
>
>Why? eval {} can warn perfectly well, if it wants to: in fact, by
>converting warnings to errors you would end up hiding warnings that
>would otherwise be printed.

I was too elliptical.  Sorry.  Expanding:

Just about anything can die, and eval will swallow the results.  You
might think that this example is so simple that it couldn't possibly
die, and so eval is perfectly harmless in this case.  However, you can
even make this die, though the only way I can think of is if to use

    use warnings FATAL => 'numeric';

and a non-numeric value of $_.

>> can't just replace do{...} with eval{...}; you'd have to add proper
>> error checking and we've recently had a discussion about the edge
>> cases to worry about.
>
>But only if you expect something to die, and only if it's not
>acceptable for the eval to (silently) return an empty list in that
>case.

As I demonstrated, surprisingly simple things can die unexpectedly.
Personally, I don't consider something to be a solution if it works
only if nothing dies, but if it doesn't it SILENTLY SUPPRESSES AN
ERROR MESSAGE.  When coding it, I'll overlook a way it can die, or
someone will not realize that it's fragile and will break the
assumptions.  And if the eval block calls some other function, in
practice it'll be utterly doomed.

In sum: you can't just replace do{...} by eval{...}, and if you try
the result will be fragile, you'll need boilerplate code to propagate
errors, and it will suppress errors or otherwise break if you get it
wrong.

-- 
Tim McDaniel, tmcd@panix.com


------------------------------

Date: Sat, 17 Mar 2012 22:53:03 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: $var = do { ... }?
Message-Id: <f7hf39-3il2.ln1@anubis.morrow.me.uk>


Quoth tmcd@panix.com:
> Concerning
>     my $result = eval {
>         $_ % 2 == 0     and return "even";
>         $_ % 3 == 0     and return "divisible by three";
>         return "just wrong";
>     };
> 
> In article <41tc39-jv12.ln1@anubis.morrow.me.uk>,
> Ben Morrow  <ben@morrow.me.uk> wrote:
> >Quoth tmcd@panix.com:
> >> In fact, the eval version is the one that needs the testing, not
> >> the sub.  eval traps fatal terminations, and just about anything
> >> can die().  In this simple case, I think you'd need
> >> "use warnings FATAL => 'numeric';"
> >
> >Why? eval {} can warn perfectly well, if it wants to: in fact, by
> >converting warnings to errors you would end up hiding warnings that
> >would otherwise be printed.
> 
> I was too elliptical.  Sorry.  Expanding:
> 
> Just about anything can die, and eval will swallow the results.  You
> might think that this example is so simple that it couldn't possibly
> die, and so eval is perfectly harmless in this case.  However, you can
> even make this die, though the only way I can think of is if to use
> 
>     use warnings FATAL => 'numeric';
> 
> and a non-numeric value of $_.

Oh, I see. Yes, I agree. There are other ways of making this die; the
most obvious would be an object in $_ with an overloaded % which dies.

Ben



------------------------------

Date: Sun, 18 Mar 2012 15:40:52 +0000
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: $var = do { ... }?
Message-Id: <87ehsp29yz.fsf@sapphire.mobileactivedefense.com>

tmcd@panix.com (Tim McDaniel) writes:
> Concerning
>     my $result = eval {
>         $_ % 2 == 0     and return "even";
>         $_ % 3 == 0     and return "divisible by three";
>         return "just wrong";
>     };
>
> In article <41tc39-jv12.ln1@anubis.morrow.me.uk>,
> Ben Morrow  <ben@morrow.me.uk> wrote:
>>Quoth tmcd@panix.com:
>>> In fact, the eval version is the one that needs the testing, not
>>> the sub.  eval traps fatal terminations, and just about anything
>>> can die().  In this simple case, I think you'd need
>>> "use warnings FATAL => 'numeric';"
>>
>>Why? eval {} can warn perfectly well, if it wants to: in fact, by
>>converting warnings to errors you would end up hiding warnings that
>>would otherwise be printed.
>
> I was too elliptical.  Sorry.  Expanding:
>
> Just about anything can die, and eval will swallow the results.

Read: It is possible to attach hidden semantics to the code above in
various ways in order to turn eval into an unsuitable solution to the
original problem. Yes, of course. Name a solution of your choice. I
will find a way to break that by violating the invariant conditions it
relies on, probably even without resorting to using, say, dynamically
linked C code to wreak havoc onto some internal data structures.

> You might think that this example is so simple that it couldn't
> possibly die, and so eval is perfectly harmless in this case.

I think that eval is 'perfectly harmless' in the sense that it will
behave according to its documentation and that you're changing your
problem specification after the fact in order to fabricate reasons
against a possible solution you don't like for 'other reasons'.

[...]

>>But only if you expect something to die, and only if it's not
>>acceptable for the eval to (silently) return an empty list in that
>>case.
>
> As I demonstrated, surprisingly simple things can die unexpectedly.
> Personally, I don't consider something to be a solution if it works
> only if nothing dies, but if it doesn't it SILENTLY SUPPRESSES AN
> ERROR MESSAGE.  When coding it, I'll overlook a way it can die, or
> someone will not realize that it's fragile and will break the
> assumptions.  And if the eval block calls some other function, in
> practice it'll be utterly doomed.

In the kind of code you are probably envisioning, where this 'other
function' probably consists of 500 - 1500 lines of code whose exact
raison d'etre was lost with some guy who left the company five years
ago, where generations of successive maintenance programmers have
added patches to the patchwork of patches in order to work around this
or that problem, this is very likely true: As soon as the code calls
another function, only God knows what's going to happen (and if we
can't catch all these weird errors, where to can we hook our next
generation of workarounds).

But that's not a universal problem.


------------------------------

Date: Sun, 18 Mar 2012 10:56:02 +0800
From: XeCycle <XeCycle@Gmail.com>
Subject: Embedding code in qq{}?
Message-Id: <87limyk471.fsf@Gmail.com>

Is it possible to use something like "${1+2}" -> "3"?

I use Emacs, and it's regex replace comes with a handy feature
that \,(any-lisp-form) in the replacement will be substituted
with the value of the expression.  I also want it in Perl, so I
read some manual, and found in s/regex/repl/ the repl is just
qq{repl}.  But I didn't find any notions of this feature.

-- 
Carl Lei (XeCycle)
Department of Physics, Shanghai Jiao Tong University
OpenPGP public key: 7795E591
Fingerprint: 1FB6 7F1F D45D F681 C845 27F7 8D71 8EC4 7795 E591


------------------------------

Date: Sat, 17 Mar 2012 23:04:48 -0400
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Embedding code in qq{}?
Message-Id: <87y5qytxrj.fsf@stemsystems.com>

>>>>> "X" == XeCycle  <XeCycle@Gmail.com> writes:

  X> Is it possible to use something like "${1+2}" -> "3"?
  X> I use Emacs, and it's regex replace comes with a handy feature
  X> that \,(any-lisp-form) in the replacement will be substituted
  X> with the value of the expression.  I also want it in Perl, so I
  X> read some manual, and found in s/regex/repl/ the repl is just
  X> qq{repl}.  But I didn't find any notions of this feature.

you are not clear in your request but my best guess is you want an
expression in the replacement part of s///. calling that a qq{} is
somewhat misleading as they do have slightly different features. but the
/e option to s/// is what you want. then the replacement is a full
expression and not a string. this is documented in perlop for s///.

uri


------------------------------

Date: Sun, 18 Mar 2012 12:14:18 +0800
From: XeCycle <XeCycle@Gmail.com>
Subject: Re: Embedding code in qq{}?
Message-Id: <87haxmk0kl.fsf@Gmail.com>

Uri Guttman <uri@stemsystems.com> writes:

[...]

> you are not clear in your request but my best guess is you want an
> expression in the replacement part of s///. calling that a qq{} is
> somewhat misleading as they do have slightly different features. but the
> /e option to s/// is what you want. then the replacement is a full
> expression and not a string. this is documented in perlop for s///.
>
> uri

Wow, thanks for that.  I read somewhere that the replacement is
simply qq{}, didn't realize this.

-- 
Carl Lei (XeCycle)
Department of Physics, Shanghai Jiao Tong University
OpenPGP public key: 7795E591
Fingerprint: 1FB6 7F1F D45D F681 C845 27F7 8D71 8EC4 7795 E591


------------------------------

Date: Sun, 18 Mar 2012 07:07:41 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: Embedding code in qq{}?
Message-Id: <jk41js$p48$1@reader1.panix.com>

In article <87limyk471.fsf@Gmail.com>, XeCycle  <XeCycle@Gmail.com>
wrote:
>Is it possible to use something like "${1+2}" -> "3"?

You made it clear in the rest of the article (which I trimmed) that
you were thinking about the right-hand side of a s///.  It turns out
that, in string contexts in general, you can do it.

Short answer:
    ${\(1+2)}

There are a couple of replies in
http://stackoverflow.com/questions/2332815/why-does-perl-evaluate-code-in-during-string-interpolation
that explain it.  I'll try to distill it.

There's a crucial sentence in "man perlref":

    Anywhere you'd put an identifier (or chain of identifiers) as part
    of a variable or subroutine name, you can replace the identifier
    with a BLOCK returning a reference of the correct type.

What does that mean?  Consider a simple scalar variable
    $foo
The identifier is "foo", so you can replace it with a block:
    ${ almost arbitrary code that evaluates to a ref to a scalar}
The only constraint is that the code has to evaluate to a reference to
a scalar.  Similarly for the array sigil
    @{ almost arbitrary code that evaluates to a ref to an array}
And I presume % and & too, though I didn't try them.

And I believe any of those can also appear in a double-quoted string.

Here's my example program (it happens to be my eighty-seventh test
script).  The stuff commented out with "##" causes the syntax errors
noted after them.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#! /usr/bin/perl
use strict;
use warnings;

my $x = 'hello';
my $y = 'world';
print "${ \$x }\n";
print "${ if (0) { \$x; } else { \$y }; }\n";
## print "hey@{1+2}there\n"; # Can't use string ("3") as an ARRAY ref while "strict refs" in use at local/test/087.pl line 9.
print "hey${\(1+2)}there\n";
$" = '<blort>';
print "hey@{[1+2, 3*4]}there\n";
## print "hey${ { \$x; last; }; \$y }there\n";
# syntax error at local/test/087.pl line 13, near "; last"
# syntax error at local/test/087.pl line 13, near "};"
# Execution of local/test/087.pl aborted due to compilation errors.
print "hey${ ; { \$x; last; }; \$y }there\n"; # Useless use of single ref constructor in void context at local/test/087.pl line 17.
print ${ \$x }, "\n";
exit 0;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The output is

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Useless use of single ref constructor in void context at
local/test/087.pl line 17.
hello
world
hey3there
hey3<blort>12there
heyworldthere
hello

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If the block evaluates to a string, then it's looked up as the name of
a dynamic variable (as in "our", not "my").  I believe that's what
it's erroring about when line 9 is uncommented.

Note that the block parsing is not quite right (in Perl 5.10),
apparently when confronted with leading "{ {", as in
    ${ { \$x; last; }; \$y }
above.  As shown above, putting in a null statement at the start
unconfuses it.

It's a "block" in the same way as do { ... } instead of { ... }: it
doesn't allow "last" (though you can throw in interior {...} to make
it work, as shown in the example), and "return" returns from an
enclosing sub rather than the block.

So, back to your original question, see
    print "hey${\(1+2)}there\n";
above, which outputs
    hey3there

-- 
Tim McDaniel, tmcd@panix.com


------------------------------

Date: Sun, 18 Mar 2012 08:37:21 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Embedding code in qq{}?
Message-Id: <1fjg39-qnv2.ln1@anubis.morrow.me.uk>


Quoth tmcd@panix.com:
> In article <87limyk471.fsf@Gmail.com>, XeCycle  <XeCycle@Gmail.com>
> wrote:
> >Is it possible to use something like "${1+2}" -> "3"?
> 
> You made it clear in the rest of the article (which I trimmed) that
> you were thinking about the right-hand side of a s///.  It turns out
> that, in string contexts in general, you can do it.
> 
> Short answer:
>     ${\(1+2)}

If you must do this, then @{[...]} is clearer, since in both cases the
internal code is evaluated in list context.

In practice it's nearly always clearer to use sprintf.

> What does that mean?  Consider a simple scalar variable
>     $foo
> The identifier is "foo", so you can replace it with a block:
>     ${ almost arbitrary code that evaluates to a ref to a scalar}
> The only constraint is that the code has to evaluate to a reference to
> a scalar.  Similarly for the array sigil
>     @{ almost arbitrary code that evaluates to a ref to an array}
> And I presume % and & too, though I didn't try them.

Yes. And *{...}.

> And I believe any of those can also appear in a double-quoted string.

Neither %{...} nor &{...} will interpolate into a double-quoted string
anyway, so you can't use them to interpolate expressions either.

Ben



------------------------------

Date: Sun, 18 Mar 2012 15:24:28 -0400
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Embedding code in qq{}?
Message-Id: <87ty1lu2z7.fsf@stemsystems.com>

>>>>> "TM" == Tim McDaniel <tmcd@panix.com> writes:

  TM> In article <87limyk471.fsf@Gmail.com>, XeCycle  <XeCycle@Gmail.com>
  TM> wrote:
  >> Is it possible to use something like "${1+2}" -> "3"?

  TM> You made it clear in the rest of the article (which I trimmed) that
  TM> you were thinking about the right-hand side of a s///.  It turns out
  TM> that, in string contexts in general, you can do it.

  TM> Short answer:
  TM>     ${\(1+2)}

bad answer. first off it isn't needed as the /e modifier to s/// does
it. secondly it is a bad idea in general. the syntax for that is clunky
and hard to read. yes, it is legal and works. i just never do it nor
teach it to anyone. it is just poor coding IMNSHO.

uri


------------------------------

Date: Sun, 18 Mar 2012 22:28:14 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: Embedding code in qq{}?
Message-Id: <jk5nht$ot8$1@reader1.panix.com>

In article <1fjg39-qnv2.ln1@anubis.morrow.me.uk>,
Ben Morrow  <ben@morrow.me.uk> wrote:
>
>Quoth tmcd@panix.com:
>> In article <87limyk471.fsf@Gmail.com>, XeCycle  <XeCycle@Gmail.com>
>> wrote:
>> >Is it possible to use something like "${1+2}" -> "3"?
>> 
>> You made it clear in the rest of the article (which I trimmed) that
>> you were thinking about the right-hand side of a s///.  It turns out
>> that, in string contexts in general, you can do it.
>> 
>> Short answer:
>>     ${\(1+2)}
>
>If you must do this, then @{[...]} is clearer, since in both cases
>the internal code is evaluated in list context.

Both are in a scalar context, I think.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#! /usr/bin/perl
use strict;
use warnings;

sub tester {
    if (wantarray) {
        print "array context\n";
        return [ 11, 12, 13 ];
    } else {
        print "scalar context\n";
        return \(22);
    }
}

print "scalar: ", ${tester()}, "\n";
print "array: ", @{tester()}, "\n";
exit 0;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Output:

$ perl local/test/088.pl
scalar context
scalar: 22
scalar context
Not an ARRAY reference at local/test/088.pl line 16.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In retrospect, that makes sense.  The ${...} and @{...} sigils want
the block to return *one reference*, which is a scalar, so why not
evaluate in scalar context?

The advantage I see for @{[BODY]} even for a scalar is that you just
need to have BODY evaluate to a normal scalar. [...] takes care of
changing it to the required reference, and @{...} converts it to an
array of one element, which within a string and a list context
evaluates to the original scalar (though of course you have to be
careful in a scalar context not to blindly use it and get the length,
1).

However, ${BODY} has to have the BODY evaluate to a reference to a
scalar, which may make \ have to spring up throughout.

-- 
Tim McDaniel, tmcd@panix.com


------------------------------

Date: Sun, 18 Mar 2012 22:33:56 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: Embedding code in qq{}?
Message-Id: <jk5nsj$ot8$2@reader1.panix.com>

In article <87ty1lu2z7.fsf@stemsystems.com>,
Uri Guttman  <uri@stemsystems.com> wrote:
>>>>>> "TM" == Tim McDaniel <tmcd@panix.com> writes:
>
>  TM> In article <87limyk471.fsf@Gmail.com>, XeCycle  <XeCycle@Gmail.com>
>  TM> wrote:
>  >> Is it possible to use something like "${1+2}" -> "3"?
>
>  TM> You made it clear in the rest of the article (which I trimmed)
>  TM> that you were thinking about the right-hand side of a s///.  It
>  TM> turns out that, in string contexts in general, you can do it.
>
>  TM> Short answer:
>  TM>     ${\(1+2)}
>
>bad answer.  first off it isn't needed as the /e modifier to s/// does
>it.

Which I tried to make clear but didn't.  I wasn't trying to address
the s/// case; everyone who pointed out s///e covered it quite nicely.
I was trying to cover the case of being outside the RHS of s///.

>secondly it is a bad idea in general. the syntax for that is clunky
>and hard to read. yes, it is legal and works. i just never do it nor
>teach it to anyone. it is just poor coding IMNSHO.

I see one use for it: @{[...]} interpolates a sub call into a quoted
string, which you could not otherwise interpolate in a string.  Since
"use constant" makes the constant be a sub, that's also how you
interpolate a "use constant" constant.  (My work systems have Perl
5.8, and I have no control over the Perl version or the Perl stock of
libraries, so I have to pretty much stick to stock Perl 5.8.)

It does help clarify for me what ${...} means, that ... is simply a
block that returns a value.

-- 
Tim McDaniel, tmcd@panix.com


------------------------------

Date: Sun, 18 Mar 2012 16:18:54 -0700
From: merlyn@stonehenge.com (Randal L. Schwartz)
Subject: Re: Embedding code in qq{}?
Message-Id: <86fwd5wl9d.fsf@red.stonehenge.com>

>>>>> "Tim" == Tim McDaniel <tmcd@panix.com> writes:

Tim> print "scalar: ", ${tester()}, "\n";

I'm amazed this works. :)

Tim> print "array: ", @{tester()}, "\n";

You forgot the square brackets.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.posterous.com/ for Smalltalk discussion


------------------------------

Date: Sun, 18 Mar 2012 19:24:06 -0400
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Embedding code in qq{}?
Message-Id: <87pqc9trvt.fsf@stemsystems.com>

>>>>> "TM" == Tim McDaniel <tmcd@panix.com> writes:

  TM> In article <87ty1lu2z7.fsf@stemsystems.com>,
  TM> Uri Guttman  <uri@stemsystems.com> wrote:
  >>>>>>> "TM" == Tim McDaniel <tmcd@panix.com> writes:
  >> 
  TM> In article <87limyk471.fsf@Gmail.com>, XeCycle  <XeCycle@Gmail.com>
  TM> wrote:
  >> >> Is it possible to use something like "${1+2}" -> "3"?
  >> 
  TM> You made it clear in the rest of the article (which I trimmed)
  TM> that you were thinking about the right-hand side of a s///.  It
  TM> turns out that, in string contexts in general, you can do it.
  >> 
  TM> Short answer:
  TM> ${\(1+2)}
  >> 
  >> bad answer.  first off it isn't needed as the /e modifier to s/// does
  >> it.

  TM> Which I tried to make clear but didn't.  I wasn't trying to address
  TM> the s/// case; everyone who pointed out s///e covered it quite nicely.
  TM> I was trying to cover the case of being outside the RHS of s///.

but the OP was only really asking about s///. he conflated the
replacement part with a "" and was wrong there.

  >> secondly it is a bad idea in general. the syntax for that is clunky
  >> and hard to read. yes, it is legal and works. i just never do it nor
  >> teach it to anyone. it is just poor coding IMNSHO.

  TM> I see one use for it: @{[...]} interpolates a sub call into a quoted
  TM> string, which you could not otherwise interpolate in a string.  Since
  TM> "use constant" makes the constant be a sub, that's also how you
  TM> interpolate a "use constant" constant.  (My work systems have Perl
  TM> 5.8, and I have no control over the Perl version or the Perl stock of
  TM> libraries, so I have to pretty much stick to stock Perl 5.8.)

it still is a poor construct to use. there is an Interpolate module that
does this with better syntax $() iirc. perl6 properly supports this idea
as well.

  TM> It does help clarify for me what ${...} means, that ... is simply a
  TM> block that returns a value.

${foo} is not such a thing. so your clarification is not totally
correct. the more i think about it, it isn't a true block in general. it is a
dereference operation that allows statements. you can't last out of it
(which you can from a bare block). so it is a limited type of block and
meant only for dereferencing. it will blow up if the last value is not
the proper ref type. a regular block need not return any value or if it
does (a do block, map block), it can return anything. there are some
serious differences so i wouldn't call it just a block.

uri



------------------------------

Date: Sun, 18 Mar 2012 19:29:17 -0400
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Embedding code in qq{}?
Message-Id: <87limxtrn6.fsf@stemsystems.com>

>>>>> "TM" == Tim McDaniel <tmcd@panix.com> writes:

  TM> In article <1fjg39-qnv2.ln1@anubis.morrow.me.uk>,
  TM> Ben Morrow  <ben@morrow.me.uk> wrote:
  >> 
  >> Quoth tmcd@panix.com:
  >>> In article <87limyk471.fsf@Gmail.com>, XeCycle  <XeCycle@Gmail.com>
  >>> wrote:
  >>> >Is it possible to use something like "${1+2}" -> "3"?
  >>> 
  >>> You made it clear in the rest of the article (which I trimmed) that
  >>> you were thinking about the right-hand side of a s///.  It turns out
  >>> that, in string contexts in general, you can do it.
  >>> 
  >>> Short answer:
  >>> ${\(1+2)}
  >> 
  >> If you must do this, then @{[...]} is clearer, since in both cases
  >> the internal code is evaluated in list context.

  TM> Both are in a scalar context, I think.

i know that to be wrong. one classic issue was that ${\bar()} always
calls in list context. there is no implicit way to get scalar context
there.
>>>>> "TM" == Tim McDaniel <tmcd@panix.com> writes:

  TM> In article <1fjg39-qnv2.ln1@anubis.morrow.me.uk>,
  TM> Ben Morrow  <ben@morrow.me.uk> wrote:
  >> 
  >> Quoth tmcd@panix.com:
  >>> In article <87limyk471.fsf@Gmail.com>, XeCycle  <XeCycle@Gmail.com>
  >>> wrote:
  >>> >Is it possible to use something like "${1+2}" -> "3"?
  >>> 
  >>> You made it clear in the rest of the article (which I trimmed) that
  >>> you were thinking about the right-hand side of a s///.  It turns out
  >>> that, in string contexts in general, you can do it.
  >>> 
  >>> Short answer:
  >>> ${\(1+2)}
  >> 
  >> If you must do this, then @{[...]} is clearer, since in both cases
  >> the internal code is evaluated in list context.

  TM> Both are in a scalar context, I think.

  TM> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  TM> #! /usr/bin/perl
  TM> use strict;
  TM> use warnings;

  TM> sub tester {
  TM>     if (wantarray) {
  TM>         print "array context\n";
  TM>         return [ 11, 12, 13 ];
  TM>     } else {
  TM>         print "scalar context\n";
  TM>         return \(22);
  TM>     }
  TM> }

  TM> print "scalar: ", ${tester()}, "\n";
  TM> print "array: ", @{tester()}, "\n";

those are not correct tests. neither is being interpolated into a string
nor is \ being used. just a dereference in code will of course provide a
scalar context as you need a single scalar value to dereference.

change the code to "scalar: ${\tester()}\n" and "array: ${[tester()]}\n"
and see what happens. that is looking at the context in interpolation.

uri



------------------------------

Date: Mon, 19 Mar 2012 00:49:45 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Embedding code in qq{}?
Message-Id: <9eci39-1da.ln1@anubis.morrow.me.uk>


Quoth Uri Guttman <uri@stemsystems.com>:
> 
> it still is a poor construct to use. there is an Interpolate module that
> does this with better syntax $() iirc. perl6 properly supports this idea
> as well.

Oddly there doesn't seem to be, at least not on CPAN. In any case, it
looks like this:
    
    package Interpolate;

    use Exporter "import";
    our @EXPORT = '%I';

    sub TIEHASH { bless \my $x }
    sub FETCH   { $_[1]        }

    tie our %I, __PACKAGE__;

    1;

and you use it like this
    
    sub ctx { wantarray ? "LIST" : defined wantarray ? "SCALAR" : "VOID" }

    say "context: $I{ctx()}";

I wonder if it only ever existed as an example in the Camel book?

(Annoyingly the obvious trick of tying %$ and %@ so you can use 
"$${ foo() }" and "@@{ foo() }" doesn't work, since they parse as
derefs. Tying %_ does work, but that's probably too many uses for '_'.
Perhaps %:?)

Ben



------------------------------

Date: Sun, 18 Mar 2012 22:12:58 +0000
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: getting hash reference from a package
Message-Id: <8739958snp.fsf@sapphire.mobileactivedefense.com>

gbacon@hiwaay.net (Greg Bacon) writes:
> Rainer Weikusat wrote
> : A singleton is the Java programmer's workaround for the fact that
> : Java requires everything to be an instance of some class, that is,
> : a general blueprint for construction objects of certain kinds, but
> : that many real-world problems are easier dealt with by systems
> : constructed of stateful modules ('subsystems') providing some kind of
> : identifiable, useful functionality for solving a part of the original
> : problem (that's similar to complex real machines which are also
> : composed of cooperating 'sub-machines' dealing with 'subtasks' of the
> : problem supposed to be solved). [...]
>
> The singleton pattern[1] isn't specific to Java even though denizens
> of that language do tend to fetishize it. Java doesn't require
> everything to be an instance of a class, the counterexample aside
> from basic types being static methods. Even so, say we have the
> module-qua-class
>
>   public class MyModule {
>     static int calls_ = 0;
>
>     public static void SayHi() {
>       ++calls_;
>       System.out.println("Hello!");
>     }
>
>     public static void SayBye() {
>       ++calls_;
>       System.out.println("Good-bye!");
>     }
>
>     public static int Calls() {
>       return calls_;
>     }
>   }
>
> MyModule fits your description above, but it is not a singleton.
> The name of the pattern derives from the constraint that a system
> may have at most a single instance of such a class. You might claim
> that a bag of static methods meets the definition in its vacuous
> sense, but such usage robs the term of its meaning.

Since there's no class instance in the example above, it obviously
doesn't make sense to call it 'a singleton'. OTOH, both serve the
same purpose: Express the concept of 'a subsystem', that is, some set
of state variables shared by some set of 'public' interface routines
intended to solve a subproblem of the problem the program containing
this code is supposed to solve, in Java. For the purpose of this
discussion, ie, the 'global variable dressed in fancy clothes' issue,
both have the same properties and there's actually nothing wrong with
that: A subsystem is isomorph to a single instance of some class
(that's exploited by the so-called 'singleton pattern') and this
implies that any single object is nothing but 'a fancily dressed
global variable'. 

> Rather than imposing the single-instance constraint, creating a
> singleton as a shortcut to bypass threading the instance through
> the call graph is a frustratingly common practice.

Hmm ... what is this supposed to mean?


------------------------------

Date: Sat, 17 Mar 2012 12:01:25 +0000
From: Henry Law <news@lawshouse.org>
Subject: Re: Increment with '#' and decrement with 'b'
Message-Id: <98KdnZ0g9-yI4PnSnZ2dnUVZ8nKdnZ2d@giganews.com>

On 17/03/12 00:54, Ben Morrow wrote:
>
> Quoth Henry Law<news@lawshouse.org>:
>>
>> I'm turning a standard musical notation for a note into a pitch.  The
>> note "A" will be zero,
>
> Do you have a reason for not starting with C? It would make more sense.

As a musician I'd say yes.  As a programmer I decided that it would make 
more sense to start at the beginning of the alphabet, as that would 
allow me to do arithmetic on ASCII values if I needed to.  It's 
arbitrary, since it's for internal representation only.

>> other way, a "#" suffix increases by 1 and "##" by two.
>
> Don't you mean 'x'?

Yes, indeed. I should have included that one too, but ## is an 
acceptable alternative when writing chord charts.  You're obviously a 
fellow muso!

>> How would a really good Perl programmer tackle this?
>
> I don't know :). I might do it like this:
>
>      no warnings "qw"; # SHUT UP!
>
>      my %pitch = qw/ A 0  B 2  H 2  C 3  D 5  E 7  F 8  G 10 /;
>      my %acc = qw(
>          # +1  b -1  x +2  ## +2  bb -2
>          is +1  es -1  s -1  isis + 2  eses -2  ses -2
>      );

That settles it; you are a musician ...

>      # Add Unicode symbols if you like :)
>
>      my ($note, $acc) = $self->{note} =~ /(.)(.*)/;
>      $self->{pitch} = $pitch{uc $note} + $acc{lc $acc};

I like that very much and it's far more elegant than some of my potato 
dumplings.  A good Kalamata olive, perhaps, or a slice of the best 
Prosciutto ...

-- 

Henry Law            Manchester, England


------------------------------

Date: Sat, 17 Mar 2012 17:05:48 +0000
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: Increment with '#' and decrement with 'b'
Message-Id: <87ty1nnonn.fsf@sapphire.mobileactivedefense.com>

Henry Law <news@lawshouse.org> writes:

[...]


> I'm turning a standard musical notation for a note into a pitch.  The
> note "A" will be zero, and the other notes on the piano, black and
> white, will range from 1 (for B flat/A sharp) up to 11 (for A flat/G
> sharp).  A "b" suffix reduces the pitch by 1; "bb" by two.  Going the
> other way, a "#" suffix increases by 1 and "##" by two.
> So D is pitch 5, Dbb is 3.  Equally D## would be 7.
>
> So I need to match the following strings to the pitches shown
>
> 0   A, Bbb, G##
> 1   A#, Bb
> 2   A##, B, Cb    ... and so on
>
> I can write code lots of ways to do this, but it has no style: it
> looks like over-cooked potato dumplings, and there's little point in
> my posting it here.

[...]


> I'm tempted to erect an enormous hash with every combination
> hard-coded in it: %pitches = (A=>0, Bbb=>0, "G\#\#"=>0, "A\#"=>1,
> Bb=>1, ... etc) and then extract the answer in one go with the hash
> lookup.

And that's what you should do: You'll need the hash lookup anyway to
turn the 'base letters' into numbers and since all mappings of some
string to a number are static, they can be precomputed once and used
without additional computation afterwards, instead of being
recalculated each time the translation needs to be made. If you think
that's too much code to write by hand, use the computer to help you:

---------------------
my %base = qw(A 0 B 2  H 2  C 3  D 5  E 7  F 8  G 10);
my $cur;

print("%pitches = qw(\n");

for (keys(%base)) {
    $cur = $base{$_};
    printf("\t%sbb %d\n\t%sb %d\n\t%s %d\n\t%s# %d\n\t%s## %d\n",
	   $_, $cur - 2,
	   $_, $cur - 1,
	   $_, $cur,
	   $_, $cur + 1,
	   $_, $cur + 2);
}

print(");\n");
---------------------

NB: If the Ab, Abb and G## bother you, it is easier to delete them
from the generated code than to special-case them in the generation
code.



------------------------------

Date: Sun, 18 Mar 2012 22:30:30 +0700
From: Ivan Shmakov <oneingray@gmail.com>
Subject: Re: Increment with '#' and decrement with 'b'
Message-Id: <86fwd63p0p.fsf@gray.siamics.net>

>>>>> Henry Law <news@lawshouse.org> writes:
>>>>> On 17/03/12 00:54, Ben Morrow wrote:
>>>>> Quoth Henry Law<news@lawshouse.org>:

	[Cross-posting to news:comp.music.misc, for obvious reasons.]

 >>> I'm turning a standard musical notation for a note into a pitch.
 >>> The note "A" will be zero,

 >> Do you have a reason for not starting with C?  It would make more
 >> sense.

 > As a musician I'd say yes.  As a programmer I decided that it would
 > make more sense to start at the beginning of the alphabet, as that
 > would allow me to do arithmetic on ASCII values if I needed to.  It's
 > arbitrary, since it's for internal representation only.

	Unfortunately, the tone-semitone interval pattern of the
	diatonic scale doesn't fit well the ASCII code, so one'd need
	some conversion table anyway.

 >>> other way, a "#" suffix increases by 1 and "##" by two.

 >> Don't you mean 'x'?

 > Yes, indeed.  I should have included that one too, but ## is an
 > acceptable alternative when writing chord charts.  You're obviously a
 > fellow muso!

	I'd like to note that there're quite a few ASCII-based music
	notations.  The ones that I'd readily recall are:

	* the one of the Lilypond [1] typesetting software (c d e f g a
	  b c makes the C major scale);

	* the ABC notation [2];

	* the Music Macro Language [3], as originated in certain 8-bit
	  implementations of the BASIC language (c d e f g a b > c makes
	  the C major scale), still surviving in such projects as QB64
	  [4], FreeBSD's spkr(4) [5] (with a few extensions), and
	  recently implemented in my MMLi project [6].

	Perhaps, it'd make sense to reuse one of the above for whatever
	project you're working on.

[1] http://lilypond.org/
[2] http://en.wikipedia.org/wiki/ABC_notation
[3] http://en.wikipedia.org/wiki/Music_Macro_Language
[4] http://www.qb64.net/
[5] http://www.gsp.com/cgi-bin/man.cgi?section=4&topic=spkr
[6] http://freecode.com/projects/mmli

[...]

-- 
FSF associate member #7257


------------------------------

Date: Sun, 18 Mar 2012 16:55:44 +0000
From: Henry Law <news@lawshouse.org>
Subject: Re: Increment with '#' and decrement with 'b'
Message-Id: <R5GdnfSAN9kNjvvSnZ2dnUVZ8gCdnZ2d@giganews.com>

On 18/03/12 15:30, Ivan Shmakov wrote:
>
> 	I'd like to note that there're quite a few ASCII-based music
> 	notations.  The ones that I'd readily recall are:
<snip>
>
> 	Perhaps, it'd make sense to reuse one of the above for whatever
> 	project you're working on.

That's really useful; I'd looked in CPAN but stopped short of doing that 
particular bit of research.

Actually in this project I'm using a notation that already exists, for 
better or worse; it's the one in the vast number of chord charts that I 
have which need transposing for different singers!  I need to be able to 
transpose C Am7 Dm7 G7#5b9 to, say, Eb Cm7 Fm7 Bb7#5b9 (and without it 
coming out as A#7#5b9 either).  And so on.

End of thread ... getting seriously off-topic!  I'd welcome 
correspondence on the subject, though.

-- 

Henry Law            Manchester, England


------------------------------

Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>


Administrivia:

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

Back issues are available via anonymous ftp from
ftp://cil-www.oce.orst.edu/pub/perl/old-digests. 

#For other requests pertaining to the digest, send mail to
#perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
#sending perl questions to the -request address, I don't have time to
#answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V11 Issue 3643
***************************************


home help back first fref pref prev next nref lref last post