[32384] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 3651 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Mar 28 00:09:26 2012

Date: Tue, 27 Mar 2012 21: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           Tue, 27 Mar 2012     Volume: 11 Number: 3651

Today's topics:
    Re: First Commercial Perl Program <ronaldljohnson@gmail.com>
    Re: naming modules <brian.d.foy@gmail.com>
    Re: naming modules <oneingray@gmail.com>
        past time <nospam.gravitalsun@hotmail.com.nospam>
    Re: past time <nospam.gravitalsun@hotmail.com.nospam>
    Re: past time <glex_no-spam@qwest-spam-no.invalid>
        subroutine exists <nospam.gravitalsun.antispam@hotmail.com.nospam>
    Re: subroutine exists <nospam.gravitalsun.antispam@hotmail.com.nospam>
    Re: subroutine exists <ben@morrow.me.uk>
    Re: subroutine exists <nospam.gravitalsun.antispam@hotmail.com.nospam>
    Re: subroutine exists <rweikusat@mssgmbh.com>
    Re: subroutine exists <nospam.gravitalsun.antispam@hotmail.com.nospam>
    Re: subroutine exists <ben@morrow.me.uk>
        Why a different result? <hslee911@yahoo.com>
    Re: Why a different result? (Tim McDaniel)
    Re: Why a different result? <hslee911@yahoo.com>
    Re: Why a different result? <ben@morrow.me.uk>
    Re: Why a different result? <ben@morrow.me.uk>
    Re: Why a different result? (Tim McDaniel)
    Re: Why a different result? <uri@stemsystems.com>
    Re: Why a different result? <uri@stemsystems.com>
    Re: Why a different result? <uri@stemsystems.com>
    Re: Why a different result? (Tim McDaniel)
    Re: Your Regex Brain <hjp-usenet2@hjp.at>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Tue, 27 Mar 2012 12:28:59 -0700 (PDT)
From: "tbb!/fbr!" <ronaldljohnson@gmail.com>
Subject: Re: First Commercial Perl Program
Message-Id: <16e3aac9-74a5-4913-88ba-92a6b36f615b@x10g2000pbi.googlegroups.com>

On Mar 10, 8:06=A0pm, "tbb!/fbr!" <ronaldljohn...@gmail.com> wrote:
> On Mar 10, 5:48=A0pm, mer...@stonehenge.com (Randal L. Schwartz) wrote:

Here's some more code I wrote for someone wanting 'random' scheduled
Twitter posts. Don't ask why, I don't even know.

I'm just wondering how the pro's would do this. Or just critique, or
even avenues of further exploration and learning.

rjohnson@cpqv2000 ~
$ cat perl.plx
#!/usr/bin/perl

use strict;
use warnings;
use List::Util qw (shuffle);

my $str=3D'1234567890!@#$
%^&*()qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM_+{}|:"<>?~`-
=3D[]\;\',./';
my @bits=3Dsplit(//,$str);
my @rnd=3Dshuffle(@bits);
print @rnd;

#for (my $count =3D 140; $count >=3D 1; $count--) {
#  my $index=3Drand @bits;
#  my $element=3D$bits[$index];
#  print "$element";
#}

You can see the commented out portion was probably the worst way to do
it. So after research I came up with the other way, which was more
elegant and made 100 times more sense (to me) and makes it much easier
to capture that @rnd output and do with it as I will without weird
conversions I would have gone through trying to mess with the
commented out portion (I would have used sprintf to get the string
into a variable, but it would have been nasty I think building a 140
char string 1 char at a time; hence the reason for the code above the
commented out portion; using perls builtin strengths and default
modules).

BTW, I do realize the functionality in the two routines are different.
The original version (commented out) allowed for repeated chars, the
other version does not.

Ron


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

Date: Tue, 27 Mar 2012 14:47:58 -0500
From: brian d foy <brian.d.foy@gmail.com>
Subject: Re: naming modules
Message-Id: <270320121447584978%brian.d.foy@gmail.com>

In article <867gy7rick.fsf@gray.siamics.net>, Ivan Shmakov
<oneingray@gmail.com> wrote:

>  [Cross-posting to news:comp.lang.perl.misc, as
>  news:comp.lang.perl.modules doesn't seems too active.]
> 
>  I've decided to put certain Perl sources to CPAN, but I'm having
>  trouble inventing some nice names for them.

We have some naming advice at:

   https://pause.perl.org/pause/query?ACTION=pause_namingmodules


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

Date: Wed, 28 Mar 2012 08:54:17 +0700
From: Ivan Shmakov <oneingray@gmail.com>
Subject: Re: naming modules
Message-Id: <8662dpij7a.fsf@gray.siamics.net>

>>>>> brian d foy <brian.d.foy@gmail.com> writes:
>>>>> Ivan Shmakov <oneingray@gmail.com> wrote:

[...]

 >> I've decided to put certain Perl sources to CPAN, but I'm having
 >> trouble inventing some nice names for them.

 > We have some naming advice at:

 > https://pause.perl.org/pause/query?ACTION=pause_namingmodules

	Indeed, I've read it first.  But it didn't answer some of my
	questions.

-- 
FSF associate member #7257


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

Date: Tue, 27 Mar 2012 14:53:56 +0300
From: "George Mpouras" <nospam.gravitalsun@hotmail.com.nospam>
Subject: past time
Message-Id: <jks9n4$24ie$1@news.ntua.gr>

You may find it useful. Returns what time was before as much days, seconds, 
etc.

You can specify also a past date as start count time.

For example what time was before 160 days?





use strict;
use warnings;
use Time::Local;

my $T = TimeUnits_to_epochtime('FROM_PAST' => time , 'days' => 160 );

print scalar localtime $T;



#   Returns the epoch seconds, from the time you specify as FROM_PAST
#   FROM_PAST  is seconds from epoch
#   You can use (more than once) the time units as keys:
#   Seconds, Minutes, Hours, Weeks, Days, Months, Years
#
#   Some usage examples:
#
#     print scalar localtime TimeUnits_to_epochtime('FROM_PAST' => time , 
'sec' => 3600, 'year' => 3 );
#     print scalar localtime TimeUnits_to_epochtime('FROM_PAST' => 23746273 
, 'minutes' => 180, 'min' => 360 , 'sec' => 120 );
#     print scalar localtime TimeUnits_to_epochtime('FROM_PAST' => 472363433 
, 'months' => 38, 'Weeks' => 3 );
#
sub TimeUnits_to_epochtime
{
my $startfrom  = -1;
my $NOW        = time;
my @NOW        = localtime $NOW;
my $Secs       = 0;
my $Months     = 0;
my $Years      = 0;
for (my ($i,$j)=(0,1); $i<=$#_; $i+=2, $j+=2) {
die "Argument ".(1+$j)." \"$_[$j]\" is not an integer\n" unless 
$_[$j]=~/^\d+$/;
if    ($_[$i]=~/(?i)^sec/){ $Secs    += $_[$j]        } # Seconds
elsif ($_[$i]=~/(?i)^min/){ $Secs    += $_[$j]*60     } # Minutes
elsif ($_[$i]=~/(?i)^hou/){ $Secs    += $_[$j]*3600   } # Hours
elsif ($_[$i]=~/(?i)^day/){ $Secs    += $_[$j]*86400  } # Days
elsif ($_[$i]=~/(?i)^wee/){ $Secs    += $_[$j]*604800 } # Weeks
elsif ($_[$i]=~/(?i)^mon/){ $Months  += $_[$j]        } # Months
elsif ($_[$i]=~/(?i)^yea/){ $Years   += $_[$j]        } # Years
elsif ($_[$i]=~/(?i)^fro/){ $startfrom= $_[$j]        } # SECONDS FROM EPOCH 
TIME that I want to look back
else  { die "Argument unit \"$_[$i]\" is not Years, Months, Weeks, Days, 
Hours, Minutes or Seconds\n" } }
die "Please define a valid seconds from epoch, for the key \"NOW\"\n" if 
$startfrom == -1;
$Years   += int $Months / 12;
$Months   = $Months % 12;
my $m     = $NOW[4] > $Months ? $NOW[4] - $Months : 12 - $Months + $NOW[4];
my $n     = Time::Local::timelocal_nocheck($NOW[0],$NOW[1],$NOW[2],$NOW[3], 
$m, ($NOW[5] - $Years));

$startfrom - ( $NOW - $n + $Secs )
} 




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

Date: Tue, 27 Mar 2012 17:38:29 +0300
From: "George Mpouras" <nospam.gravitalsun@hotmail.com.nospam>
Subject: Re: past time
Message-Id: <jksjc7$r2p$1@news.ntua.gr>

some corrections


use strict;
use warnings;
use Time::Local 'timelocal_nocheck';

#print scalar localtime TimeUnits_to_epochtime('Weeks' => 6 );
print scalar localtime TimeUnits_to_epochtime('Months' => 4 );


#   Returns the epoch seconds, from the time you specify as FROM_PAST
#   FROM_PAST  is seconds from epoch
#   You can use (more than once) the time units as keys:
#   Seconds, Minutes, Hours, Weeks, Days, Months, Years
#
#   Some usage examples:
#
#     print scalar localtime TimeUnits_to_epochtime(   'months' => 38, 
'Weeks' => 3 );
#     print scalar localtime TimeUnits_to_epochtime('FROM_PAST' => time , 
'sec' => 3600, 'year' => 3 );
#     print scalar localtime TimeUnits_to_epochtime('FROM_PAST' => 23746273 
, 'minutes' => 180, 'min' => 360 , 'sec' => 120 );
#
sub TimeUnits_to_epochtime
{
my $startfrom  = $^T;
my @NOW        = localtime $^T;
my $Secs       = 0;
my $Months     = 0;
my $Years      = 0;
for (my ($i,$j)=(0,1); $i<=$#_; $i+=2, $j+=2) {
die "Argument ".(1+$j)." \"$_[$j]\" is not an integer\n" unless 
$_[$j]=~/^\d+$/;
if    ($_[$i]=~/(?i)^sec/){ $Secs    += $_[$j]        } # Seconds
elsif ($_[$i]=~/(?i)^min/){ $Secs    += $_[$j]*60     } # Minutes
elsif ($_[$i]=~/(?i)^hou/){ $Secs    += $_[$j]*3600   } # Hours
elsif ($_[$i]=~/(?i)^day/){ $Secs    += $_[$j]*86400  } # Days
elsif ($_[$i]=~/(?i)^wee/){ $Secs    += $_[$j]*604800 } # Weeks
elsif ($_[$i]=~/(?i)^mon/){ $Months  += $_[$j]        } # Months
elsif ($_[$i]=~/(?i)^yea/){ $Years   += $_[$j]        } # Years
elsif ($_[$i]=~/(?i)^fro/){ $startfrom= $_[$j]        } # SECONDS FROM EPOCH 
TIME that I want to look back
else  { die "Argument unit \"$_[$i]\" is not Years, Months, Weeks, Days, 
Hours, Minutes or Seconds\n" } }
$Years   += int $Months / 12;
$Months   = $Months % 12;
my ($m,$y);

 if ( $NOW[4] > $Months ) {
 $m = $NOW[4] - $Months;
 $y = $NOW[5] - $Years
 }
 else {
 $m = 12 - $Months + $NOW[4];
 $y = $NOW[5] - $Years - 1
 }

$startfrom  -  $^T  +  timelocal_nocheck(@NOW[0..3],$m,$y)  -  $Secs
} 




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

Date: Tue, 27 Mar 2012 10:10:59 -0500
From: "J. Gleixner" <glex_no-spam@qwest-spam-no.invalid>
Subject: Re: past time
Message-Id: <4f71d883$0$73602$815e3792@news.qwest.net>

On 03/27/12 06:53, George Mpouras wrote:
> You may find it useful. Returns what time was before as much days, seconds,
> etc.

ahhhh.. You do know there are many date classes that have been around 
for many, many years that do this, and much, much more.. right?



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

Date: Wed, 28 Mar 2012 01:04:48 +0300
From: "George Mpouras" <nospam.gravitalsun.antispam@hotmail.com.nospam>
Subject: subroutine exists
Message-Id: <jktdi0$1g8i$1@news.ntua.gr>

How can I find if a subroutine exists without try to call it ?


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

Date: Wed, 28 Mar 2012 02:07:20 +0300
From: "George Mpouras" <nospam.gravitalsun.antispam@hotmail.com.nospam>
Subject: Re: subroutine exists
Message-Id: <jkth78$1t3m$1@news.ntua.gr>

I think I found it


my $var = 'f2';
print   ref *{__PACKAGE__.::.$var}{CODE} ;


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

Date: Wed, 28 Mar 2012 00:07:17 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: subroutine exists
Message-Id: <5qt949-gbk2.ln1@anubis.morrow.me.uk>


Quoth "George Mpouras" <nospam.gravitalsun.antispam@hotmail.com.nospam>:
> How can I find if a subroutine exists without try to call it ?

    defined &sub

Note that this will return false for a sub that has been declared (like 

    sub foo;

) but not given a definition. You can check for a stub like that with
*foo{CODE}, though this isn't usually useful.

What do you think you need this for? It's likely that you ought to be
using a dispatch table instead.

Ben



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

Date: Wed, 28 Mar 2012 03:27:02 +0300
From: "George Mpouras" <nospam.gravitalsun.antispam@hotmail.com.nospam>
Subject: Re: subroutine exists
Message-Id: <jktlsl$2mk6$1@news.ntua.gr>

I have to check if an external  package have a method or not (windows , 
linux) 



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

Date: Wed, 28 Mar 2012 01:40:39 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: subroutine exists
Message-Id: <87d37xy2uw.fsf@sapphire.mobileactivedefense.com>

"George Mpouras" <nospam.gravitalsun.antispam@hotmail.com.nospam>
writes:
> I have to check if an external  package have a method or not (windows
> , linux) 

That a symbol table entry pointing at a code reference exists at the
moment doesn't necessarily mean it will still exist by the time it is
supposed to be used and vice-versa. In particular, this check won't
find anything an AUTOLOAD sub will either create or emulate.


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

Date: Wed, 28 Mar 2012 04:10:55 +0300
From: "George Mpouras" <nospam.gravitalsun.antispam@hotmail.com.nospam>
Subject: Re: subroutine exists
Message-Id: <jktoev$2vcn$1@news.ntua.gr>

correct. It is a little bit more complicated. I know that my methods exists, 
but they should not try to call something that do not exist, autoload 
automation does not help a alot

Ο "Rainer Weikusat"  έγραψε στο μήνυμα 
news:87d37xy2uw.fsf@sapphire.mobileactivedefense.com...

"George Mpouras" <nospam.gravitalsun.antispam@hotmail.com.nospam>
writes:
> I have to check if an external  package have a method or not (windows
> , linux)

That a symbol table entry pointing at a code reference exists at the
moment doesn't necessarily mean it will still exist by the time it is
supposed to be used and vice-versa. In particular, this check won't
find anything an AUTOLOAD sub will either create or emulate. 



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

Date: Wed, 28 Mar 2012 02:28:52 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: subroutine exists
Message-Id: <k36a49-q8m2.ln1@anubis.morrow.me.uk>


Quoth "George Mpouras" <nospam.gravitalsun.antispam@hotmail.com.nospam>:
> I have to check if an external  package have a method or not (windows , 
> linux) 

Ah: you said 'function', not 'method'. The correct check for a method is
to use ->can:

    Some::Package->can("some_method")

This will also detect inherited methods, which is important.

A correct AUTOLOAD implementation will also supply a ->can method which
gives the right answers (though this is surprisingly difficult to get
right, in practice, and not all modules do it correctly).

In principle an object can respond to different methods from its class;
one example of this would be Test::MockObject. If you might have to deal
with objects like this you should be sure to call ->can on the
appropriate object rather than on the class.

A different tactic is just to call the method in an eval{} and handle
the failure appropriately.

Ben



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

Date: Tue, 27 Mar 2012 12:40:41 -0700 (PDT)
From: James <hslee911@yahoo.com>
Subject: Why a different result?
Message-Id: <df2af1a9-5176-47d0-a1c3-cacc7f2aae4b@t8g2000pbe.googlegroups.com>

Expect the same output, but differ. Why?

use Data::Dumper;

undef %o, %e;
for $f (1..$N) {
if ($f%2) { $o{$f}= -1 } else { $e{$f}=1 }
}
print Dumper \%o; print Dumper \%e;

undef %o, %e;
for $f (1..$N) {
$f%2 ? $o{$f}= -1 : $e{$f}=1;
}
print Dumper \%o; print Dumper \%e;

(output)

$VAR1 = {
          '1' => -1,
          '3' => -1,
          '7' => -1,
          '9' => -1,
          '5' => -1
        };
$VAR1 = {
          '8' => 1,
          '6' => 1,
          '4' => 1,
          '10' => 1,
          '2' => 1
        };
$VAR1 = {
          '1' => 1,
          '3' => 1,
          '7' => 1,
          '9' => 1,
          '5' => 1
        };
$VAR1 = {
          '8' => 1,
          '6' => 1,
          '4' => 1,
          '10' => 1,
          '2' => 1
        };

James


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

Date: Tue, 27 Mar 2012 20:18:34 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: Why a different result?
Message-Id: <jkt7aq$sdq$1@reader1.panix.com>

In article <df2af1a9-5176-47d0-a1c3-cacc7f2aae4b@t8g2000pbe.googlegroups.com>,
James  <hslee911@yahoo.com> wrote:
>Expect the same output, but differ. Why?
>
>use Data::Dumper;
>
>undef %o, %e;
>for $f (1..$N) {
>if ($f%2) { $o{$f}= -1 } else { $e{$f}=1 }
>}
>print Dumper \%o; print Dumper \%e;
>
>undef %o, %e;
>for $f (1..$N) {
>$f%2 ? $o{$f}= -1 : $e{$f}=1;
>}
>print Dumper \%o; print Dumper \%e;

It's helpful to post real programs that run, because then people can
immediately copy and paste it, run "-MO=Deparse,-p", or whatnot.

See the precedence table near the top of "man perlop".
Assignment operators bind more loosely than ?:, so the second method
is equivalent to

    ($f%2 ? $o{$f}= -1 : $e{$f}) = 1;

Assignments return lvalues that you can assign to again, so on odd
numbers $o{$f} gets assigned -1 and then it gets stomped with 1.

You can see this with

    $ perl -MO=Deparse,-p -e '$f%2 ? $o{$f}= -1 : $e{$f}=1;'
    ((($f % 2) ? ($o{$f} = (-1)) : $e{$f}) = 1);
    -e syntax OK

I'll add numbers (in a fixed-width font) to show the paren pairing:

    ((($f % 2) ? ($o{$f} = (-1)) : $e{$f}) = 1);
    123      3   3         4  43         2    1

Personally, I don't use ?: much, partially because it can sometimes
lead to too-complicated expressions, and partially because it can
cause precedence problems like this.  Parenthesizing liberally in ?:
can be a good idea.

-- 
Tim McDaniel, tmcd@panix.com


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

Date: Tue, 27 Mar 2012 13:39:36 -0700 (PDT)
From: James <hslee911@yahoo.com>
Subject: Re: Why a different result?
Message-Id: <74c6cb4e-eb6a-433a-acfe-ba073577e72f@pg2g2000pbb.googlegroups.com>

On Mar 27, 1:18=A0pm, t...@panix.com (Tim McDaniel) wrote:
> In article <df2af1a9-5176-47d0-a1c3-cacc7f2aa...@t8g2000pbe.googlegroups.=
com>,
>
>
>
>
>
>
>
>
>
> James =A0<hslee...@yahoo.com> wrote:
> >Expect the same output, but differ. Why?
>
> >use Data::Dumper;
>
> >undef %o, %e;
> >for $f (1..$N) {
> >if ($f%2) { $o{$f}=3D -1 } else { $e{$f}=3D1 }
> >}
> >print Dumper \%o; print Dumper \%e;
>
> >undef %o, %e;
> >for $f (1..$N) {
> >$f%2 ? $o{$f}=3D -1 : $e{$f}=3D1;
> >}
> >print Dumper \%o; print Dumper \%e;
>
> It's helpful to post real programs that run, because then people can
> immediately copy and paste it, run "-MO=3DDeparse,-p", or whatnot.
>
> See the precedence table near the top of "man perlop".
> Assignment operators bind more loosely than ?:, so the second method
> is equivalent to
>
> =A0 =A0 ($f%2 ? $o{$f}=3D -1 : $e{$f}) =3D 1;
>
> Assignments return lvalues that you can assign to again, so on odd
> numbers $o{$f} gets assigned -1 and then it gets stomped with 1.
>
> You can see this with
>
> =A0 =A0 $ perl -MO=3DDeparse,-p -e '$f%2 ? $o{$f}=3D -1 : $e{$f}=3D1;'
> =A0 =A0 ((($f % 2) ? ($o{$f} =3D (-1)) : $e{$f}) =3D 1);
> =A0 =A0 -e syntax OK
>
> I'll add numbers (in a fixed-width font) to show the paren pairing:
>
> =A0 =A0 ((($f % 2) ? ($o{$f} =3D (-1)) : $e{$f}) =3D 1);
> =A0 =A0 123 =A0 =A0 =A03 =A0 3 =A0 =A0 =A0 =A0 4 =A043 =A0 =A0 =A0 =A0 2 =
=A0 =A01
>
> Personally, I don't use ?: much, partially because it can sometimes
> lead to too-complicated expressions, and partially because it can
> cause precedence problems like this. =A0Parenthesizing liberally in ?:
> can be a good idea.
>
> --
> Tim McDaniel, t...@panix.com

Thanks. So parenthesizing individual expressions is the key.
($f%2) ? ($o{$f}=3D -1) : ($e{$f}=3D1) ;

James


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

Date: Tue, 27 Mar 2012 21:40:26 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Why a different result?
Message-Id: <q6l949-bei2.ln1@anubis.morrow.me.uk>


Quoth James <hslee911@yahoo.com>:
> Expect the same output, but differ. Why?
> 
> use Data::Dumper;
> 
> undef %o, %e;
> for $f (1..$N) {
> if ($f%2) { $o{$f}= -1 } else { $e{$f}=1 }
> }
> print Dumper \%o; print Dumper \%e;
> 
> undef %o, %e;
> for $f (1..$N) {
> $f%2 ? $o{$f}= -1 : $e{$f}=1;

?: binds tighter than =, so this is equivalent to

    ($f % 2 ? $o{$f} = -1 : $e{$f}) = 1;

When $f is even, this reduces to

    $e{$f} = 1;

as you want, but when $f is odd it reduces to

    ($o{$f} = -1) = 1;

which is not what you meant. If you insist on using ?: for flow control,
you need to parenthesise both parts, like this

    $f % 2 ? ($o{$f} = -1) : ($e{$f} = 1);

(Strictly speaking you don't need to parenthesise the first part unless
it contains more ?:s, but it would be a bit weird not to.)

You can also use and...or, but only if you are certain the 'if' part
will always return a true value:

    $f % 2 and $o{$f} = -1 or $e{$f} = 1;

Ben



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

Date: Tue, 27 Mar 2012 21:50:40 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Why a different result?
Message-Id: <0ql949-bei2.ln1@anubis.morrow.me.uk>


Quoth tmcd@panix.com:
> 
> Personally, I don't use ?: much, partially because it can sometimes
> lead to too-complicated expressions, and partially because it can
> cause precedence problems like this.  Parenthesizing liberally in ?:
> can be a good idea.

As I think I've said before, I disagree here. A tree of ?: *on the RHS
of an assignment* is a simple and clear way to represent a list of
(potentially quite complicated) cases.

If you find yourself needing to parenthesise, you're using it for flow
control rather than as an expression, and you should switch to if/else
or given/when instead. This is basically the same rule-of-thumb that
tells you when to use and/or rather than &&/||.

Ben



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

Date: Tue, 27 Mar 2012 21:14:26 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: Why a different result?
Message-Id: <jktajh$iu0$1@reader1.panix.com>

In article <q6l949-bei2.ln1@anubis.morrow.me.uk>,
Ben Morrow  <ben@morrow.me.uk> wrote:
>
>Quoth James <hslee911@yahoo.com>:
>> $f%2 ? $o{$f}= -1 : $e{$f}=1;
>
>?: binds tighter than =, so this is equivalent to
>    ($f % 2 ? $o{$f} = -1 : $e{$f}) = 1;
 ...
>You can also use and...or, but only if you are certain the 'if' part
>will always return a true value:
>
>    $f % 2 and $o{$f} = -1 or $e{$f} = 1;

It took me a minute to figure out that you meant that the *then* part
must always return true.  (If the "if" part always returned true,
there'd be no need for a conditional!) You make a good point.  Indeed,

    $f % 2 and $o{$f} = 0 or $e{$f} = 0;

would set both %o and %e for odd numbers.

    $f % 2 and ($o{$f} = 0, 1) or $e{$f} = 0;

looks odd and fragile, and is no improvement over a parenthesized ?: .

The idiom works much more reliably in Bourne-like shells, because
commands' boolean value is based on their exit code, not usually the
arithmentic result of an operation:

    (( f % 2 )) && echo "$f is odd" || echo "$f is even"

-- 
Tim McDaniel, tmcd@panix.com


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

Date: Tue, 27 Mar 2012 17:44:04 -0400
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Why a different result?
Message-Id: <87y5qlpvmj.fsf@stemsystems.com>

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

  TM> Personally, I don't use ?: much, partially because it can sometimes
  TM> lead to too-complicated expressions, and partially because it can
  TM> cause precedence problems like this.  Parenthesizing liberally in ?:
  TM> can be a good idea.

then you are thinking incorrectly about ?:. it is an expression and not
meant for side effects. = is an assignment and a side effect. if you
just use ?: to select one of two expressions it generally works well
with no precedence issues. and it is usually cleaner than the longer
if/else with redundant assignments. in fact if the lvalue is more then a
variable then the ?: will be much cleaner than an if/else and less prone
to bugs. when you have redundant code, you have to make sure both parts
are the same, you need to change both if one is changed, and the reader
of the code has to check both to see they are the same. ?: eliminates
the redundancy and all that wasteful work.

uri


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

Date: Tue, 27 Mar 2012 17:47:55 -0400
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Why a different result?
Message-Id: <87ty19pvg4.fsf@stemsystems.com>

>>>>> "J" == James  <hslee911@yahoo.com> writes:

  J> Expect the same output, but differ. Why?
  J> use Data::Dumper;

  J> undef %o, %e;

others have answered the ?: issue. i want to address that line of
code. it is wrong in several ways.

first off it isn't even needed before the first loop. secondly it
doesn't do what you think it does. the proper way to clear hashes is to
assign an empty list to them:

	%o = () ;

undef is not meant to be used on aggregates (arrays and hashes). it not
only clears the data, it reclaims all storage inside it. and it leads to
a worse problem which is using defined on aggregates to see if they have
any elements. and that is very wrong as defined on a hash which has been
undef'ed will be false but if is ever had elements but was empty now,
defined on it will be true. and that is almost never what you expect. so
the rule is don't use undef on aggregates and never use defined on them.

uri


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

Date: Tue, 27 Mar 2012 17:49:56 -0400
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Why a different result?
Message-Id: <87pqbxpvcr.fsf@stemsystems.com>

>>>>> "J" == James  <hslee911@yahoo.com> writes:

  J> Thanks. So parenthesizing individual expressions is the key.
  J> ($f%2) ? ($o{$f}= -1) : ($e{$f}=1) ;

NO! using ?: the correct way is the key. it is for returning one
expression from the pair. it is NOT for side effects like assignment or
calling functions. if you need that, use if/else. the first version of
the code you had is correct. the second is incorrect and should not be
fixed with parens. that compounds the problem.

uri



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

Date: Wed, 28 Mar 2012 03:38:38 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: Why a different result?
Message-Id: <jku13u$r0o$1@reader1.panix.com>

In article <87pqbxpvcr.fsf@stemsystems.com>,
Uri Guttman  <uri@stemsystems.com> wrote:
>>>>>> "J" == James  <hslee911@yahoo.com> writes:
>
>  J> Thanks. So parenthesizing individual expressions is the key.
>  J> ($f%2) ? ($o{$f}= -1) : ($e{$f}=1) ;
>
>NO! using ?: the correct way is the key. it is for returning one
>expression from the pair. it is NOT for side effects like assignment
>or calling functions.

It was made to work, though with some difficulty, so it is a large
terminological inexactitude to call it flatly "incorrect" and to yell
"NO!"

But it is pointless at best.  The only plausible use of ?: really is
for evaluating the results of expressions *for use in a larger
expression*.  If the results of the right-hand sides are not needed,
as in this particular example, ?: gains nothing over a plain
if-then-else.  For example, it's like calling two subs with

    2*a() - b()/17;

What's the point of the useless arithmetic?  That example would be
clearer as just

    a(); b();

Further, the original poster hit a pitfall, a point of fragility, due
to precedence -- and much worse, it was a silent bug.

Moreover, others and I generally think it's worse style the more
complicated and side-effecty a ?" expression gets.

So while it cannot be called "incorrect", I think most people would
strongly recommend against the above example.

-- 
Tim McDaniel, tmcd@panix.com


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

Date: Tue, 27 Mar 2012 14:40:34 +0200
From: "Peter J. Holzer" <hjp-usenet2@hjp.at>
Subject: Re: Your Regex Brain
Message-Id: <slrnjn3da2.7or.hjp-usenet2@hrunkner.hjp.at>

["Followup-To:" header set to comp.lang.perl.misc.]
On 2012-03-27 00:02, sln@netherlands.com <sln@netherlands.com> wrote:
> This is more like a regex brain.
>
> '
><img 
>   (?=\s) 
>   (?= (?:[^>"\']|"[^"]*"|\'[^\']*\')*? (?<=\s) width \s*=
>       (?: (?> \s* ([\'"]) \s* (?<WIDTH>.*?) \s* \g{-2} )
>         | (?> (?!\s*[\'"]) \s* (?<WIDTH>[^\s>]*) (?=\s|>) )   
>       )
>   )
>   (?= (?:[^>"\']|"[^"]*"|\'[^\']*\')*? (?<=\s) src \s*=
>       (?: (?> \s* ([\'"]) \s* (?<SRC>.*?) \s* \g{-2} )
>         | (?> (?!\s*[\'"]) \s* (?<SRC>[^\s>]*) (?=\s|>) )   
>       )
>   )
>   (?= (?:[^>"\']|"[^"]*"|\'[^\']*\')*? (?<=\s) height \s*=
>       (?: (?> \s* ([\'"]) \s* (?<HEIGHT>.*?) \s* \g{-2} )
>         | (?> (?!\s*[\'"]) \s* (?<HEIGHT>[^\s>]*) (?=\s|>) )   
>       )
>   )
>   (?= (?:[^>"\']|"[^"]*"|\'[^\']*\')*? (?<=\s) alt \s*=
>       (?: (?> \s* ([\'"]) \s* (?<ALT>.*?) \s* \g{-2} )
>         | (?> (?!\s*[\'"]) \s* (?<ALT>[^\s>]*) (?=\s|>) )   
>       )
>   )
>   (?> \s+ (?:".*?"|\'.*?\'|[^>]*?)+ > ) (?<!/>)
> '

"This is your brain on drugs."

    SCNR,
    	hp


-- 
   _  | Peter J. Holzer    | Deprecating human carelessness and
|_|_) | Sysadmin WSR       | ignorance has no successful track record.
| |   | hjp@hjp.at         | 
__/   | http://www.hjp.at/ |  -- Bill Code on asrg@irtf.org


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

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


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