[32375] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 3642 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Mar 16 21:09:34 2012

Date: Fri, 16 Mar 2012 18:09:16 -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           Fri, 16 Mar 2012     Volume: 11 Number: 3642

Today's topics:
    Re: $var = do { ... }? <ben@morrow.me.uk>
    Re: $var = do { ... }? <rvtol+usenet@xs4all.nl>
    Re: $var = do { ... }? <rweikusat@mssgmbh.com>
    Re: $var = do { ... }? (Tim McDaniel)
    Re: $var = do { ... }? <rweikusat@mssgmbh.com>
    Re: $var = do { ... }? (Tim McDaniel)
    Re: $var = do { ... }? <rweikusat@mssgmbh.com>
    Re: $var = do { ... }? <ben@morrow.me.uk>
    Re: $var = do { ... }? <rweikusat@mssgmbh.com>
    Re: %hash + @keys -> @value_refs; existing associations <oneingray@gmail.com>
    Re: getting hash reference from a package (Greg Bacon)
        Increment with '#' and decrement with 'b' <news@lawshouse.org>
    Re: Increment with '#' and decrement with 'b' <ben@morrow.me.uk>
        Mouse Module Question <edgrsprj@ix.netcom.com>
    Re: reduce, anyone? <oneingray@gmail.com>
    Re: yet another question about numbers and strings (hymie!)
    Re: yet another question about numbers and strings <ben@morrow.me.uk>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Fri, 16 Mar 2012 00:18:42 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: $var = do { ... }?
Message-Id: <2gda39-ljc2.ln1@anubis.morrow.me.uk>


Quoth tmcd@panix.com:
> 
> So I have to make sure the code evaluates the desired return value as
> the last thing in the block, like
> 
>     my $result = do {
>         if ($i % 2 == 0) { 'even' }
>         elsif ($i % 3 == 0) { 'divisible by 3' }
>         elsif ($i % 5 == 0) { 'divisible by 5' }
>         else { 'just wrong' }
>     };
> 
> Is there a clever way in Perl 5 to metaphorically return early with a
> value?

I don't think so, though as of 5.14 you can use 'given' as an expression
so you could write that

    my $result = do {
        given ($i) {
            "even"                  when $_ % 2 == 0;
            "divisible by three"    when $_ % 3 == 0;
            "divisible by five"     when $_ % 5 == 0;
            "just wrong";
        }
    };

This won't work in 5.10 or 5.12, and neither the 'do' nor the 'given' is
optional, but it's something.

The other thing that works, and it is in fact documented though I had no
idea until I just looked, is to return from an eval {}:

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

I'm not sure it's got much to recommend it over

    my $result = sub {
        $_ % 2 == 0     and return "even";
        return "odd";
    }->();

though, unless you want the exception-catching.

In any case, if you're pushing this much logic into a do{} block you
probably need to dike it out into its own sub.

Ben



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

Date: Fri, 16 Mar 2012 14:08:13 +0100
From: "Dr.Ruud" <rvtol+usenet@xs4all.nl>
Subject: Re: $var = do { ... }?
Message-Id: <4f633b3d$0$6845$e4fe514c@news2.news.xs4all.nl>

On 2012-03-15 18:09, Tim McDaniel wrote:

> So I have to make sure the code evaluates the desired return value as
> the last thing in the block, like
>
>      my $result = do {
>          if ($i % 2 == 0) { 'even' }
>          elsif ($i % 3 == 0) { 'divisible by 3' }
>          elsif ($i % 5 == 0) { 'divisible by 5' }
>          else { 'just wrong' }
>      };
>
> Is there a clever way in Perl 5 to metaphorically return early with a
> value?

That if/elsif/else of yours already does that. Remember that 
perl-the-binary compiles to opcodes. So the 'elsif' is only done if the 
'if' didn't do.

perl -Mstrict -wle '
   my $i = $ARGV[0];
   my $result = !$i       ? "0"
              : !($i % 2) ? "2-fold"
              : !($i % 3) ? "3-fold"
              : !($i % 5) ? "5-fold"
              : "bah";
   print $result;
' -- -21
3-fold

-- 
Ruud


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

Date: Fri, 16 Mar 2012 14:25:20 +0000
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: $var = do { ... }?
Message-Id: <871uosoc6n.fsf@sapphire.mobileactivedefense.com>

Ben Morrow <ben@morrow.me.uk> writes:
> Quoth tmcd@panix.com:

[...]

>>     my $result = do {
>>         if ($i % 2 == 0) { 'even' }
>>         elsif ($i % 3 == 0) { 'divisible by 3' }
>>         elsif ($i % 5 == 0) { 'divisible by 5' }
>>         else { 'just wrong' }
>>     };
>> 
>> Is there a clever way in Perl 5 to metaphorically return early with a
>> value?

[...]

> The other thing that works, and it is in fact documented though I had no
> idea until I just looked, is to return from an eval {}:
>
>     my $result = eval {
>         $_ % 2 == 0     and return "even";
>         $_ % 3 == 0     and return "divisible by three";
>         return "just wrong";
>     };
>
> I'm not sure it's got much to recommend it over
>
>     my $result = sub {
>         $_ % 2 == 0     and return "even";
>         return "odd";
>     }->();
>
> though,

The first is using a language construct according to its intended
purpose. The second is abusing a language construct in order to
emulate the first 'somehow'. That alone should be sufficient to avoid
it. In addition to that, it needs more test because the mock
subroutine created for this purpose also needs to be invoked and -
depending on whether the compiler special-cases this so that people
can indulge their passion for the bizarre[*] - it is probably also
less efficient.

	[*] 'Xah Lee' should like it, however, since it is quite
	'mathy' ...


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

Date: Fri, 16 Mar 2012 15:25:10 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: $var = do { ... }?
Message-Id: <jjvm0m$lp7$1@reader1.panix.com>

In article <4f633b3d$0$6845$e4fe514c@news2.news.xs4all.nl>,
Dr.Ruud <rvtol+usenet@xs4all.nl> wrote:
>On 2012-03-15 18:09, Tim McDaniel wrote:
>
>> So I have to make sure the code evaluates the desired return value as
>> the last thing in the block, like
>>
>>      my $result = do {
>>          if ($i % 2 == 0) { 'even' }
>>          elsif ($i % 3 == 0) { 'divisible by 3' }
>>          elsif ($i % 5 == 0) { 'divisible by 5' }
>>          else { 'just wrong' }
>>      };
>>
>> Is there a clever way in Perl 5 to metaphorically return early with a
>> value?
>
>That if/elsif/else of yours already does that.

Yes, I know.  I was giving an example where the desired final value is
the last thing evaluated, and then asking what I could do if that
happens not to be the case.  The next (badly contrived) example I gave
was such a case, with the 'even' case returning early and the first
"elsif" changed to an "if".

>   my $result = !$i       ? "0"
>              : !($i % 2) ? "2-fold"
>              : !($i % 3) ? "3-fold"
>              : !($i % 5) ? "5-fold"
>              : "bah";

My question was prompted bya ?: chain like that, except with much
larger and more complicated expressions, and embedded in a much larger
and much more complicated expression.  I began idly musing on
different ways it could be avoided, other than the obvious ones of
factoring it into a sub, moving it to an if-elsif-else above the much
more complicated block, and so forth.

-- 
Tim McDaniel, tmcd@panix.com


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

Date: Fri, 16 Mar 2012 17:46:09 +0000
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: $var = do { ... }?
Message-Id: <87mx7gh21q.fsf@sapphire.mobileactivedefense.com>

"Dr.Ruud" <rvtol+usenet@xs4all.nl> writes:
> On 2012-03-15 18:09, Tim McDaniel wrote:
>
>> So I have to make sure the code evaluates the desired return value as
>> the last thing in the block, like
>>
>>      my $result = do {
>>          if ($i % 2 == 0) { 'even' }
>>          elsif ($i % 3 == 0) { 'divisible by 3' }
>>          elsif ($i % 5 == 0) { 'divisible by 5' }
>>          else { 'just wrong' }
>>      };
>>
>> Is there a clever way in Perl 5 to metaphorically return early with a
>> value?
>
> That if/elsif/else of yours already does that. Remember that
> perl-the-binary compiles to opcodes. So the 'elsif' is only done if
> the 'if' didn't do.

"When the program compiles, the machine is happy" (R. Pike). But since
code is not write-only, there should be other considerations beyond
'making the machine happy'. The way and if - else construct works is
that it provides, based on some set of conditions, a set of
alternative codepaths to follow at some point of an otherwise linear
movement, ie, after one of the alternate code paths was chosen,
execution is supposed to continue with the next statement after the
if. People tend to use it even if no such next statement exists, at
least partially cause by a misunderstanding of some statement about
'structure programming', namely, that 'a module' (subroutine) should
have a single entry and exit point. This essentially doesn't make any
sense[*] in language designed with this dictum in mind because
subroutines always have a single entry point and they always have a
single exit point (that's the location where execution of the calling
code continues after the subroutine finished(!)). Later, this
statement has been re-interpreted to mean that the control-flow inside
a subroutine should be contorted to give the illusion as if all
possible codepaths through the subroutine would 'naturally' end after
the last statement in the corresponding block. And that's IMO not a
good idea.



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

Date: Fri, 16 Mar 2012 21:01:31 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: $var = do { ... }?
Message-Id: <jk09nb$ong$1@reader1.panix.com>

In article <871uosoc6n.fsf@sapphire.mobileactivedefense.com>,
Rainer Weikusat  <rweikusat@mssgmbh.com> wrote:
>Ben Morrow <ben@morrow.me.uk> writes:
>> Quoth tmcd@panix.com:
>
>[...]
>
>>>     my $result = do {
>>>         if ($i % 2 == 0) { 'even' }
>>>         elsif ($i % 3 == 0) { 'divisible by 3' }
>>>         elsif ($i % 5 == 0) { 'divisible by 5' }
>>>         else { 'just wrong' }
>>>     };
>>> 
>>> Is there a clever way in Perl 5 to metaphorically return early with a
>>> value?
>
>[...]
>
>> The other thing that works, and it is in fact documented though I had no
>> idea until I just looked, is to return from an eval {}:
>>
>>     my $result = eval {
>>         $_ % 2 == 0     and return "even";
>>         $_ % 3 == 0     and return "divisible by three";
>>         return "just wrong";
>>     };
>>
>> I'm not sure it's got much to recommend it over
>>
>>     my $result = sub {
>>         $_ % 2 == 0     and return "even";
>>         return "odd";
>>     }->();
>>
>> though,
>
>The first is using a language construct according to its intended
>purpose.  The second is abusing a language construct in order to
>emulate the first 'somehow'. That alone should be sufficient to avoid
>it. In addition to that, it needs more test because the mock
>subroutine created for this purpose also needs to be invoked and -
>depending on whether the compiler special-cases this so that people
>can indulge their passion for the bizarre[*] - it is probably also
>less efficient.

I infer that "first" means the eval example and "second" means the sub
example.

The notion of "abusing a language construct" in Perl is already a
problematic notion.  Perl is the polyperverted abuse bottom of
languages.

The doc for eval says "This form is typically used to trap exceptions
more efficiently than the first (see below), while also providing the
benefit of checking the code within BLOCK at compile time."  So using
eval just to be able to return is not its "intended purpose".

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';".  More realistic examples can die much easier.  So you
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.

sub{...}, on the other hand, *is* a straightforward substitution.
Also, for people like me who are used to Lisp and similar languages
that make much more use of small functions created all over, it's a
natural idiom.  Also, it has an argument list, so some complexity
could be encapsulated there, allowing the body of the text to refer to
$_[2] or assigning the argument to a variable as one likes.

I don't know how to test efficiency.  I've seen a few uses of some
module to run a construct a number of times and report on the time,
but I apparently wasn't using the correct search terms at CPAN.

-- 
Tim McDaniel, tmcd@panix.com


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

Date: Fri, 16 Mar 2012 21:37:03 +0000
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: $var = do { ... }?
Message-Id: <871uosw7ls.fsf@sapphire.mobileactivedefense.com>

tmcd@panix.com (Tim McDaniel) writes:
> In article <871uosoc6n.fsf@sapphire.mobileactivedefense.com>,
> Rainer Weikusat  <rweikusat@mssgmbh.com> wrote:
>>Ben Morrow <ben@morrow.me.uk> writes:
>>> Quoth tmcd@panix.com:
>>
>>[...]
>>
>>>>     my $result = do {
>>>>         if ($i % 2 == 0) { 'even' }
>>>>         elsif ($i % 3 == 0) { 'divisible by 3' }
>>>>         elsif ($i % 5 == 0) { 'divisible by 5' }
>>>>         else { 'just wrong' }
>>>>     };
>>>> 
>>>> Is there a clever way in Perl 5 to metaphorically return early with a
>>>> value?
>>
>>[...]
>>
>>> The other thing that works, and it is in fact documented though I had no
>>> idea until I just looked, is to return from an eval {}:
>>>
>>>     my $result = eval {
>>>         $_ % 2 == 0     and return "even";
>>>         $_ % 3 == 0     and return "divisible by three";
>>>         return "just wrong";
>>>     };
>>>
>>> I'm not sure it's got much to recommend it over
>>>
>>>     my $result = sub {
>>>         $_ % 2 == 0     and return "even";
>>>         return "odd";
>>>     }->();
>>>
>>> though,
>>
>>The first is using a language construct according to its intended
>>purpose.  The second is abusing a language construct in order to
>>emulate the first 'somehow'. That alone should be sufficient to avoid
>>it. In addition to that, it needs more test because the mock
>>subroutine created for this purpose also needs to be invoked and -
>>depending on whether the compiler special-cases this so that people
>>can indulge their passion for the bizarre[*] - it is probably also
>>less efficient.
>
> I infer that "first" means the eval example and "second" means the sub
> example.
>
> The notion of "abusing a language construct" in Perl is already a
> problematic notion. Perl is the polyperverted abuse bottom of
> languages.

The Perl code some people write is 'the polyperverted abuse bottom of
coding', this being enabled by the versatility of the language.

> The doc for eval says "This form is typically used to trap exceptions
> more efficiently than the first (see below), while also providing the
> benefit of checking the code within BLOCK at compile time."  So using
> eval just to be able to return is not its "intended purpose".

this text continues with

	In both forms, the value returned is the value of the last
	expression evaluated inside the mini-program; a return
	statement may be also used, just as with subroutines. 

> 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';".  More realistic examples can die much easier.  So you
> 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.

Almost anything can be turned from a molehill into an insurmountable
moutain by sufficiently wild generalizations. None of this is an issue
for the actual example and there is a single 'edge case' code using
eval for exception handling needs to worry about (There are two more
if some module written by some confused guy is being used. But since
these 'edge cases' have been fixed in Perl 5.14.0, there's little
reason to do so).

> sub{...}, on the other hand, *is* a straightforward substitution.
> Also, for people like me who are used to Lisp and similar languages
> that make much more use of small functions created all over, it's a
> natural idiom.

If you want to make it a subroutine then do so. That would be a
sensible choice. Recreating an otherwise invariable anonymous
subroutine every time the code is executed in order to call it once
just to avoid structuring the code as hard as possible isn't.


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

Date: Fri, 16 Mar 2012 22:56:04 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: $var = do { ... }?
Message-Id: <41tc39-jv12.ln1@anubis.morrow.me.uk>


Quoth tmcd@panix.com:
> In article <871uosoc6n.fsf@sapphire.mobileactivedefense.com>,
> Rainer Weikusat  <rweikusat@mssgmbh.com> wrote:
> >Ben Morrow <ben@morrow.me.uk> writes:
> >> Quoth tmcd@panix.com:
> >
> >>> Is there a clever way in Perl 5 to metaphorically return early with a
> >>> value?
> >
> >> The other thing that works, and it is in fact documented though I had no
> >> idea until I just looked, is to return from an eval {}:
> >>
> >>     my $result = eval {
> >>         $_ % 2 == 0     and return "even";
> >>         $_ % 3 == 0     and return "divisible by three";
> >>         return "just wrong";
> >>     };
> >>
> >> I'm not sure it's got much to recommend it over
> >>
> >>     my $result = sub {
> >>         $_ % 2 == 0     and return "even";
> >>         return "odd";
> >>     }->();
> >>
> >> though,
> >
> >The first is using a language construct according to its intended
> >purpose.  The second is abusing a language construct in order to
> >emulate the first 'somehow'. That alone should be sufficient to avoid
> >it. In addition to that, it needs more test because the mock
> >subroutine created for this purpose also needs to be invoked and -
> >depending on whether the compiler special-cases this so that people
> >can indulge their passion for the bizarre[*] - it is probably also
> >less efficient.
> 
> I infer that "first" means the eval example and "second" means the sub
> example.

I don't know what Rainer meant, but I would have said the reverse: using
eval {} as an anon sub rather than a try is not using it for its
intended purpose...

> The doc for eval says "This form is typically used to trap exceptions
> more efficiently than the first (see below), while also providing the
> benefit of checking the code within BLOCK at compile time."  So using
> eval just to be able to return is not its "intended purpose".

 ...and I see you agree :).

> 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. Even if you went to the trouble of catching
and printing them, Perl (5) doesn't have resumable exceptions, so
there'd be no way to get back the normal warning behaviour.

> More realistic examples can die much easier.  So you
> 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. If you
remember, the most important thing I said was 'if you use raw eval{},
check its return value rather than relying on $@', which is exactly what
you're doing here.

> sub{...}, on the other hand, *is* a straightforward substitution.
> Also, for people like me who are used to Lisp and similar languages
> that make much more use of small functions created all over, it's a
> natural idiom.  Also, it has an argument list, so some complexity
> could be encapsulated there, allowing the body of the text to refer to
> $_[2] or assigning the argument to a variable as one likes.

There'd be little point, since it's a lexical closure. That is, you can
simply refer to outside variables without needing to pass them in.

> I don't know how to test efficiency.  I've seen a few uses of some
> module to run a construct a number of times and report on the time,
> but I apparently wasn't using the correct search terms at CPAN.

Benchmark; it's in the core distribution.

I would expect that, if there's any measurable difference, eval is
slower than sub is slower than a plain block is slower than do, simply
because each is doing everything the next does and then a bit more.

Ben



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

Date: Fri, 16 Mar 2012 23:54:51 +0000
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: $var = do { ... }?
Message-Id: <874ntoaypg.fsf@sapphire.mobileactivedefense.com>

Ben Morrow <ben@morrow.me.uk> writes:

[...]

>> More realistic examples can die much easier.  So you
>> 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. If you
> remember, the most important thing I said was 'if you use raw eval{},
> check its return value rather than relying on $@',

In absence of a 'special return value to signal an error condition'
convention the code happens to use, the return value from an eval can
be anything, including 0 or undef. Consequently, this doesn't and
cannot ever work except if the code isn't using exceptions for error
reporting but special return values. 

[...]

> There'd be little point, since it's a lexical closure. That is, you can
> simply refer to outside variables without needing to pass them in.
>
>> I don't know how to test efficiency.  I've seen a few uses of some
>> module to run a construct a number of times and report on the time,
>> but I apparently wasn't using the correct search terms at CPAN.
>
> Benchmark; it's in the core distribution.
>
> I would expect that, if there's any measurable difference, eval is
> slower than sub is slower than a plain block is slower than do, simply
> because each is doing everything the next does and then a bit more.

As a someone named Daniel Bernstein once quipped "Don't
speculate. Profile". For the extremely simple-minded example below,

----------
use Benchmark;

timethese(-5,
	  {
	   eval => sub {
	       return eval { return 3; };
	   },

	   sub => sub {
	       return sub { return 3; }->();
	   }});
----------

creating an anonymous throwaway subroutine per invocation is about
half as fast as the eval. This might be different when avoiding this
grotty hack in favor of using a proper, named subroutine (you can
always name it Maeusedreck if you fear that this might render your
code a tad bit to accessible to others ...)


			      



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

Date: Fri, 16 Mar 2012 14:04:18 +0700
From: Ivan Shmakov <oneingray@gmail.com>
Subject: Re: %hash + @keys -> @value_refs; existing associations only
Message-Id: <86mx7h3u31.fsf@gray.siamics.net>

>>>>> Martijn Lievaart <m@rtij.nl.invlalid> writes:
>>>>> On Thu, 15 Mar 2012 13:44:01 +0700, Ivan Shmakov wrote:

 >> I wonder, is it necessary to use map to get a list of references
 >> /considering the existing associations only/?

 >> my @refs
 >>     = map { exists ($hash{$_}) ? \$hash{$_} : undef; } (@keys);

 >> I don't care about the missing keys, BTW.  Thus, I can use something
 >> like the following instead, but it's even more verbose.

[...]

 > my @refs
 >     = map { exists ($hash{$_}) ? \$hash{$_} : () } (@keys);

	Indeed.  Thanks!

	Now I'd combine that with List::Util::reduce to get...

$ perl -we 'use strict;
            use Data::Dump;
            use List::Util qw (reduce);
            my $obj = {
                "a" => { "b" => "c" },
                "d" => { "e" => { "f" => "g" }, "h" => "i" },
                "j" => "k"
            };
            my @krefs
                = ([qw (a b)], [qw (d e f)], [qw (d h)], [qw (j)]);
            foreach my $kr (@krefs) {
                print (join (".", @$kr),
                       " = ",
                       (reduce { $a->{$b}; } ($obj, @$kr)),
                       "\n");
            }'
Name "main::b" used only once: possible typo at -e line 1.
Name "main::a" used only once: possible typo at -e line 1.
a.b = c
d.e.f = g
d.h = i
j = k
$ 

	Though I wonder whether I can use a subroutine reference instead
	of a code block or not?

-- 
FSF associate member #7257


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

Date: Fri, 16 Mar 2012 12:11:09 -0500
From: gbacon@hiwaay.net (Greg Bacon)
Subject: Re: getting hash reference from a package
Message-Id: <1tOdnQun9cWw6f7SnZ2dnUVZ_vCdnZ2d@posted.hiwaay2>

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.

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. It's a global
variable dressed up in fancy clothes but comes with all the same
headaches.

[1]: http://en.wikipedia.org/wiki/Singleton_pattern

Greg
-- 
 ... the several states who formed [the Constitution], being sovereign and
independent, have the unquestionable right to judge of its infraction; and
that a nullification, by those sovereignties, of all unauthorized acts done
under colour of that instrument, is the rightful remedy ... -- Ky. Resolution


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

Date: Fri, 16 Mar 2012 23:39:19 +0000
From: Henry Law <news@lawshouse.org>
Subject: Increment with '#' and decrement with 'b'
Message-Id: <Au6dnWYprLy6Uv7SnZ2dnUVZ8g-dnZ2d@giganews.com>

Although I've had a lot of practice writing Perl I often feel that I'm 
not really a Perl programmer because the finer points of Perl style -- 
the things that really make Perl what it is -- aren't in the front of my 
mind.  I would like help with a simple task which, try though I might, 
still looks really laborious the way I've written it.

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 can extract the basic pitch of the note reasonably elegantly with a 
hash, like this

  my %pitches = ( A=>0, B=>2, C=>3, D=>5 ... etc), followed by
  my $this_pitch = $pitches{ $this_letter };

But every time I try to allow for the accidentals I end up with tedious 
"if" statements, or multiple increments/decrements like this

     $self->{pitch}-- if (lc $acc) eq 'b';
     $self->{pitch}-- if (lc $acc) eq 'bb';
     ... and the opposite for the "\#" cases

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.

How would a really good Perl programmer tackle this?

-- 

Henry Law            Manchester, England


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

Date: Sat, 17 Mar 2012 00:54:49 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Increment with '#' and decrement with 'b'
Message-Id: <pv3d39-ov32.ln1@anubis.morrow.me.uk>


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.

> 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.

Don't you mean 'x'?

<snip>
> I can extract the basic pitch of the note reasonably elegantly with a 
> hash, like this
> 
>   my %pitches = ( A=>0, B=>2, C=>3, D=>5 ... etc), followed by
>   my $this_pitch = $pitches{ $this_letter };
> 
> But every time I try to allow for the accidentals I end up with tedious 
> "if" statements, or multiple increments/decrements like this
> 
>      $self->{pitch}-- if (lc $acc) eq 'b';
>      $self->{pitch}-- if (lc $acc) eq 'bb';
>      ... and the opposite for the "\#" cases
> 
> 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.
> 
> 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
    );
    # Add Unicode symbols if you like :)

    my ($note, $acc) = $self->{note} =~ /(.)(.*)/;
    $self->{pitch} = $pitch{uc $note} + $acc{lc $acc};

Ben



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

Date: Fri, 16 Mar 2012 13:30:03 -0500
From: "E.D.G." <edgrsprj@ix.netcom.com>
Subject: Mouse Module Question
Message-Id: <jPednfgqr4s6G_7SnZ2dnUVZ_vednZ2d@earthlink.com>

ActiveState Perl 5.10 is being used on Windows XP and higher Personal 
Computers.

       Several of us are working with a variety of computer programs 
including Perl, Gnuplot, and Basic to develop a shared application that 
draws maps.

       We would like the program to display small pop-up windows with 
additional information when the computer mouse pointer is positioned over an 
object on a Gnuplot window.  A Perl program is already constantly running in 
the background with that application and checking for key presses.  It could 
also constantly check the computer mouse pointer location.

Question:  What Perl module would be the simplest one to use for obtaining X 
and Y coordinate information for the computer mouse?  There appear to be 
quite a few modules to choose from.

Question:  Is there a Perl module that can generate pop-up windows on its 
own based on the mouse pointer location?



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

Date: Fri, 16 Mar 2012 13:34:08 +0700
From: Ivan Shmakov <oneingray@gmail.com>
Subject: Re: reduce, anyone?
Message-Id: <86ty1p3vhb.fsf@gray.siamics.net>

>>>>> Ben Morrow <ben@morrow.me.uk> writes:
>>>>> Quoth Ivan Shmakov <oneingray@gmail.com>:

 >> Since the days of APL, reduction (or folding) is one of the basic
 >> operations on ordered collections (lists, arrays, etc.)

 >> I see that Perl 6 has such an operator [1], but what about Perl 5?
 >> A quick search on CPAN reveals [2] (though it seems to implement
 >> APL's scan instead of reduce), but I still wonder if there're any
 >> other possible choices?  (It's not that hard to implement such a
 >> function, BTW.)

 > List::Util has the standard implementation.

	Thanks!

	Moreover, it also defines first (), so that I can now use
	first (defined, @a) instead of my own either (@a).

-- 
FSF associate member #7257


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

Date: 16 Mar 2012 16:42:45 GMT
From: hymie@lactose.homelinux.net (hymie!)
Subject: Re: yet another question about numbers and strings
Message-Id: <4f636d85$0$18687$882e7ee2@usenet-news.net>

In our last episode, the evil Dr. Lacto had captured our hero,
  Ben Morrow <ben@morrow.me.uk>, who said:
>
>At a guess: you are using a 32bit build of perl, and it isn't built with
>-Duse64bitint?

No, I'm pretty sure (but not positive) that it's a 64-bit perl.

This is perl, v5.8.5 built for x86_64-linux-thread-multi
    use64bitint=define use64bitall=define uselongdouble=undef
    optimize='-O2 -g -pipe -m64',
    libpth=/usr/local/lib64 /lib64 /usr/lib64
  Compile-time options: DEBUGGING MULTIPLICITY USE_ITHREADS USE_64_BIT_INT
                      USE_64_BIT_ALL USE_LARGE_FILES PERL_IMPLICIT_CONTEXT

>At a further guess: you are using DBD::Sybase version 1.09 or older?

Yes, I am using Sybase 1.07  .

> * In DBD::Sybase 1.09 and before, certain large numeric types (money,
> * bigint) were being kept in native format, and then returned to the
> * caller as a perl NV data item. An NV is really a float, so there was
> * loss of precision, especially for bigint data which is a 64bit int.

I will look into updating it to a newer version.  Thanks for the tip.

--hymie!    http://lactose.homelinux.net/~hymie    hymie@lactose.homelinux.net
-------------------------------------------------------------------------------


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

Date: Fri, 16 Mar 2012 17:03:35 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: yet another question about numbers and strings
Message-Id: <7c8c39-l3t1.ln1@anubis.morrow.me.uk>


Quoth hymie@lactose.homelinux.net (hymie!):
> In our last episode, the evil Dr. Lacto had captured our hero,
>   Ben Morrow <ben@morrow.me.uk>, who said:
> >
> >At a guess: you are using a 32bit build of perl, and it isn't built with
> >-Duse64bitint?
> 
> No, I'm pretty sure (but not positive) that it's a 64-bit perl.
> 
> This is perl, v5.8.5 built for x86_64-linux-thread-multi
>     use64bitint=define use64bitall=define uselongdouble=undef

Yes, it is. That means old versions of DBD::Sybase must have used a
(56-bit) NV to return a 64-bit SQL bigint, even when a 64-bit IV was
available. Yuck.

Ben



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

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 3642
***************************************


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