[33081] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4357 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Jan 27 09:09:19 2015

Date: Tue, 27 Jan 2015 06:09:05 -0800 (PST)
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 Jan 2015     Volume: 11 Number: 4357

Today's topics:
        Global, Local, Static (was: Twelve Drummers Drumming) <see.my.sig@for.my.address>
    Re: Global, Local, Static <gravitalsun@hotmail.foo>
    Re: Global, Local, Static <see.my.sig@for.my.address>
    Re: Global, Local, Static <rweikusat@mobileactivedefense.com>
        soap web service <gravitalsun@hotmail.foo>
        Why are these brackets necessary? <see.my.sig@for.my.address>
    Re: Why are these brackets necessary? <news@todbe.com>
    Re: Why are these brackets necessary? <marius@ieval.ro>
    Re: Why are these brackets necessary? <see.my.sig@for.my.address>
    Re: Why are these brackets necessary? <see.my.sig@for.my.address>
    Re: Why are these brackets necessary? <justin.1410@purestblue.com>
    Re: Why are these brackets necessary? <justin.1410@purestblue.com>
    Re: Why are these brackets necessary? <rweikusat@mobileactivedefense.com>
    Re: Why are these brackets necessary? <ben.usenet@bsb.me.uk>
    Re: Why are these brackets necessary? <see.my.sig@for.my.address>
    Re: Why are these brackets necessary? <ben.usenet@bsb.me.uk>
    Re: Why are these brackets necessary? <rweikusat@mobileactivedefense.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Tue, 27 Jan 2015 01:37:22 -0800
From: Robbie Hatley <see.my.sig@for.my.address>
Subject: Global, Local, Static (was: Twelve Drummers Drumming)
Message-Id: <Y8-dnRyg7ZTPwVrJnZ2dnUVZ57ydnZ2d@giganews.com>


On 12/28/2014 10:51 AM, Rainer Weikusat wrote:
 > Robbie Hatley <see.my.sig@for.my.address> writes:
 > > ...
 > > $::ordinals[ 1] = "first";
 > > $::ordinals[ 2] = "second";
 > > ...
 > > $::gifts[ 1] = "a partridge in a pear tree.\n";
 > > $::gifts[ 2] = "two turtle doves,\nand ";
 > > ...
 > ...
 > Unless you specifically want to use objects referred to by the symbol
 > table of the package for some reason, you'd IMHO be better advised to
 > use my than our.

Oh, I was just shamelessly polluting the "main" namespace by dumping
loads of crap into its symbol table, just because everyone says I'm
not supposed to. :-)

For one thing, I'd never actually used a Perl global variable before,
and it took me a while to figure out how to do it, as Perl books tend
not to use them at all. But I figured out that I could create global
variables by using names starting with "$::", which is short for
"$main::".

At least "$::variable" is one way to make sure that an entire
program has access to that data. For better and for worse.

I worked at one company where the programmers (writing in C)
made nearly ALL of the variables in their software global.

On the plus side, the info was available everywhere, so there was
much less need to pass data on the stack via function arguments.

But on the minus side, functions in different parts of the program
would often get into fights over the value of a variable, sometimes
attempting to use the same variable name for very different purposes.
because the programmer could no longer keep track of the morass of
hundreds of global variables.

So when I ended up maintaining that code (the persons who wrote it
having been laid off due to corporate downsizing), I struggled to
localize as many of those variables as possible to reel-in the
confusion.

The rule of thumb I came up with was, if a piece of data is only
needed in one function, make it local. Two functions, keep it
local to one function and pass as an argument to the other. Three
or more functions, make it global. And if I needed to retain data
in a function when exiting and re-entering, I made the variable
"static".

But Perl is a whole different beast, so I'm not sure how much
of what I learned about C variables is transferable.

QUESTION: Are there any Perl-specific downsides to making
variables global ($main::variable) that I should know about?

QUESTION: Is there any Perl equivalent to C's "static"
variables (which retain their value between function calls)?


-- 
Curious,
Robbie Hatley
Midway City, CA, USA
perl -E 'say "\154o\156e\167o\154f\100w\145ll\56c\157m\n";'
https://www.facebook.com/robbie.hatley



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

Date: Tue, 27 Jan 2015 12:09:40 +0200
From: George Mpouras <gravitalsun@hotmail.foo>
Subject: Re: Global, Local, Static
Message-Id: <ma7o46$29eo$1@news.ntua.gr>

> variables global ($main::variable) that I should know about?
>
> QUESTION: Is there any Perl equivalent to C's "static"
> variables (which retain their value between function calls)?
>

use strict;use warnings; use feature 'say';

my $var = 100;

&Fun_preserve;
say $var;

&Fun_brake;
say $var;

sub Fun_brake    { $var = 0 }
sub Fun_preserve { my $var = 0 }

#  use our ... to define a variable
# in a package and be visible from the
# colling main calling program



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

Date: Tue, 27 Jan 2015 05:36:22 -0800
From: Robbie Hatley <see.my.sig@for.my.address>
Subject: Re: Global, Local, Static
Message-Id: <f8KdnVaQk9DLCVrJnZ2dnUVZ57ydnZ2d@giganews.com>


On 01/27/2015 02:09 AM, George Mpouras wrote:

>> QUESTION: Is there any Perl equivalent to C's "static"
>> variables (which retain their value between function calls)?
>>
>
> use strict;use warnings; use feature 'say';
>
> my $var = 100;
>
> &Fun_preserve;
> say $var;
>
> &Fun_brake;
> say $var;
>
> sub Fun_brake    { $var = 0 }
> sub Fun_preserve { my $var = 0 }

Interesting, but none of those variables have any similarity to
C's "static" variables:

#include "stdio.h"
void Retain (void);
int main (void)
{
    Retain();
    Retain();
    Retain();
    return 0;
}
void Retain (void)
{
    static int Fred = 37;         /* initialized first time ONLY    */
    printf("Fred = %d\n", Fred);  /* Fred holds value between calls */
    ++Fred;                       /* 38, 39, 40                     */
    return;                       /* exit, but Fred retains value   */
}

Prints:

37
38
39


So....  any way of doing that in Perl subroutines?


-- 
Cheers,
Robbie Hatley
Midway City, CA, USA
perl -le 'print "\154o\156e\167o\154f\100w\145ll\56c\157m"'
https://www.facebook.com/robbie.hatley



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

Date: Tue, 27 Jan 2015 13:59:14 +0000
From: Rainer Weikusat <rweikusat@mobileactivedefense.com>
Subject: Re: Global, Local, Static
Message-Id: <87386w8gul.fsf@doppelsaurus.mobileactivedefense.com>

Robbie Hatley <see.my.sig@for.my.address> writes:
> On 01/27/2015 02:09 AM, George Mpouras wrote:
>>> QUESTION: Is there any Perl equivalent to C's "static"
>>> variables (which retain their value between function calls)?
>>>
>>
>> use strict;use warnings; use feature 'say';
>>
>> my $var = 100;
>>
>> &Fun_preserve;
>> say $var;
>>
>> &Fun_brake;
>> say $var;
>>
>> sub Fun_brake    { $var = 0 }
>> sub Fun_preserve { my $var = 0 }
>
> Interesting, but none of those variables have any similarity to
> C's "static" variables:
>
> #include "stdio.h"
> void Retain (void);
> int main (void)
> {
>    Retain();
>    Retain();
>    Retain();
>    return 0;
> }
> void Retain (void)
> {
>    static int Fred = 37;         /* initialized first time ONLY    */
>    printf("Fred = %d\n", Fred);  /* Fred holds value between calls */
>    ++Fred;                       /* 38, 39, 40                     */
>    return;                       /* exit, but Fred retains value   */
> }
>
> Prints:
>
> 37
> 38
> 39
>
>
> So....  any way of doing that in Perl subroutines?

Two, actually. A 'traditional' one, create a my variable in a scope only
the subroutine can access,

--------
{
    my $fred = 37;
    
    sub retain
    {
	print("$fred\n");
	++$fred;
    }
}

retain();
retain();
retain();
---------

or use a 'state' variable (if available),

---------
use feature 'state';

sub retain
{
    state $fred = 37;
    print("$fred\n");
    ++$fred;
}

retain();
retain();
retain();
---------


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

Date: Tue, 27 Jan 2015 11:44:31 +0200
From: George Mpouras <gravitalsun@hotmail.foo>
Subject: soap web service
Message-Id: <ma7ml1$24ii$1@news.ntua.gr>

I asked to create a soap web service. I know almost nothing about.
Any hints of what modules to use or anything else useful ?


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

Date: Sun, 25 Jan 2015 19:55:06 -0800
From: Robbie Hatley <see.my.sig@for.my.address>
Subject: Why are these brackets necessary?
Message-Id: <3aWdnRgvqpE9J1jJnZ2dnUVZ57ydnZ2d@giganews.com>

I was writing a script yesterday which gives both current
GMT time (in 24Hr time scale) and current local time (AM/PM).
To convert the hour and meridian (AM/PM indicator), I first
tried code like this:

given ($L_hour) {
    when (0) {
       $hour = 12;
       $meri = "AM";
    }
    when (1..11) {
       $hour = $L_hour;
       $meri = "AM";
    }
    when (12) {
       $hour = 12;
       $meri = "PM";
    }
    when (13..23) {
       $hour = $L_hour - 12;
       $meri = "PM";
    }
    default {
       $hour = 0;
       $meri = "WTF???";
    }
}

But, that didn't work; gave errors on the range-operators.
So I found an example of a range used as a when test in a
Given in The Camel Book, which used brackets around the
range, like so:
    ...
    when ([1..11]) {...}
    ...
    when ([13..23]) {...}
    ...
And that worked. But I'm not sure why. What exactly are
those brackets doing there, anyway?


-- 
Cheers,
Robbie Hatley
lonewolf AT well DOT com


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

Date: Sun, 25 Jan 2015 21:17:27 -0800
From: "$Bill" <news@todbe.com>
Subject: Re: Why are these brackets necessary?
Message-Id: <54C5CDE7.4060808@todbe.com>

On 1/25/2015 19:55, Robbie Hatley wrote:
> I was writing a script yesterday which gives both current
> GMT time (in 24Hr time scale) and current local time (AM/PM).
> To convert the hour and meridian (AM/PM indicator), I first
> tried code like this:

I'm still using 5.12 - not about to play with experimental features.  :)

Why not just make a hash and then
	$hour = $hash{$L_hour}{'hour'};
	$meri = $hash{$L_hour}{'meri'} ;
and you're done ?

> given ($L_hour) {
>     when (0) {
>        $hour = 12;
>        $meri = "AM";
>     }
>     when (1..11) {
>        $hour = $L_hour;
>        $meri = "AM";
>     }
>     when (12) {
>        $hour = 12;
>        $meri = "PM";
>     }
>     when (13..23) {
>        $hour = $L_hour - 12;
>        $meri = "PM";
>     }
>     default {
>        $hour = 0;
>        $meri = "WTF???";
>     }
> }
>
> But, that didn't work; gave errors on the range-operators.
> So I found an example of a range used as a when test in a
> Given in The Camel Book, which used brackets around the
> range, like so:
>     ...
>     when ([1..11]) {...}
>     ...
>     when ([13..23]) {...}
>     ...
> And that worked. But I'm not sure why. What exactly are
> those brackets doing there, anyway?




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

Date: Mon, 26 Jan 2015 10:24:37 +0200
From: Marius Gavrilescu <marius@ieval.ro>
Subject: Re: Why are these brackets necessary?
Message-Id: <87ppa2kkze.fsf@ieval.ro>

--=-=-=
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable

Robbie Hatley <see.my.sig@for.my.address> writes:

> But, that didn't work; gave errors on the range-operators.
> So I found an example of a range used as a when test in a
> Given in The Camel Book, which used brackets around the
> range, like so:
>    ...
>    when ([1..11]) {...}
>    ...
>    when ([13..23]) {...}
>    ...
> And that worked. But I'm not sure why. What exactly are
> those brackets doing there, anyway?

See "Switch Statements" in perldoc perlsyn and "Smartmatch Operator" in
perldoc perlop for the gory details.

The "when" condition cannot be a list. It must be something from the
table in "Smartmatch Operator". Relevant snippet:

     Right operand is an ARRAY:

     Left      Right      Description and pseudocode
     =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
     Any       ARRAY      smartmatch each ARRAY element[3]
                    like: grep { Any ~~ $_ } ARRAY

which means that if an array(ref) is supplied to when, it will match if
$_ smartmatches any of the elements of the array(ref).

However, smartmatch and given/when are experimental and their behaviour
can change. You should generally use something like Switch::Plain instead.
=2D-=20
Marius Gavrilescu

--=-=-=
Content-Type: application/pgp-signature; name="signature.asc"

-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1

iQIcBAEBCgAGBQJUxfnFAAoJEMoENb5ewbNi36IQAILbzK04s/E/HLF5qvuyxaZO
OWuQxv8t/Noew6WtEw0vPJpj2s+Yl2EzO+fuk/ZH7pQzsRUv/zWabv4brVhCX+h2
hlCJhQbGcQ+iiSqHOT2X4fZSNsu0m1yUrGmYkgPODbrfszm6nofdQ2ELhDJUh2uH
c0hfnzW3vW+0X6SQRI0KJh0z/kS8Sadd8SGeu572kbPZg8JC5ZwgdDI+L6pB/1QG
qXbfb/NGYqQtsuwa/3wx67HQJFcX8i+vKu8JKGAweQFKU0/VUQ9Uhz7WPZZMh/S5
eZhxr08J9EDvmAC/R8jJzBBImd9x90h/YLneCbJIVenlDrkwb7SKjFrn8STBkHjI
ol0xVkpiRtOj+zmYr+7HDLeW+M3augBOcmEWGtldqZ5HbNTa9+ctbPkNIK+enrb2
im5/sew7T6nK29ANddkXOTIO4ayHHo4iPc4eVwylAHXQw91toiJFKsYSIXMdwa3N
LimpKdJm1JdDqQK4XEtWN/zWNdcEOfiKxuppun6+YduPYtk34xvPSE8xyROzACY5
ZleG8nUZpJpTmIiJB21qmlFm0Pb3i8wCgfyRi04M1EIDJimsbOMSxw/xhTHbCFSk
n5gGQUksjNLlQzOzu5tI+BeZC1UVYq0hDzHyf/rtVFcV/CGDGpiAdMXYlLzKOcUU
k62F0uoRESOWZ7nCO6JZ
=rPCX
-----END PGP SIGNATURE-----
--=-=-=--


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

Date: Mon, 26 Jan 2015 01:20:25 -0800
From: Robbie Hatley <see.my.sig@for.my.address>
Subject: Re: Why are these brackets necessary?
Message-Id: <PISdnbcFuflOm1vJnZ2dnUVZ572dnZ2d@giganews.com>

On 1/25/2015 9:17 PM, $Bill wrote:

 > On 1/25/2015 19:55, Robbie Hatley wrote:
 > > I was writing a script yesterday which gives both current
 > > GMT time (in 24Hr time scale) and current local time (AM/PM).
 > > To convert the hour and meridian (AM/PM indicator), I first
 > > tried code like this:
 >
 > I'm still using 5.12 - not about to play with experimental features.  :)
 >
 > Why not just make a hash and then
 >      $hour = $hash{$L_hour}{'hour'};
 >      $meri = $hash{$L_hour}{'meri'} ;
 > and you're done ?

Ah, that's a good idea. Or better, since $L_hour is always an integer
in the range 0-23, and we're indexing on that, just use an array of
refs to 2-element arrays. Lemme try that... Yes, works.  Yep, I like
the following better than what I was doing with the given statement:


#! /usr/bin/perl
# "localtime.perl"

my @months = qw(January   February  March     April
                 May       June      July      August
                 September October   November  December);

my @days   = qw(Sunday    Monday    Tuesday   Wednesday
                 Thursday  Friday    Saturday);

my ($L_sec,  $L_min,  $L_hour,
     $L_mday, $L_mon,  $L_year,
     $L_wday, $L_yday, $L_isdst)
     = localtime;

my @hourmeri =
(
    [12, 'AM'], [ 1, 'AM'], [ 2, 'AM'], [ 3, 'AM'], [ 4, 'AM'], [ 5, 'AM'],
    [ 6, 'AM'], [ 7, 'AM'], [ 8, 'AM'], [ 9, 'AM'], [10, 'AM'], [11, 'AM'],
    [12, 'PM'], [ 1, 'PM'], [ 2, 'PM'], [ 3, 'PM'], [ 4, 'PM'], [ 5, 'PM'],
    [ 6, 'PM'], [ 7, 'PM'], [ 8, 'PM'], [ 9, 'PM'], [10, 'PM'], [11, 'PM'],
);

my $hour = $hourmeri[$L_hour]->[0];
my $meri = $hourmeri[$L_hour]->[1];

printf
(
    "\nCurrent Local time is %02d:%02d:%02d%2s on %s %s %d, %d\n",
    $hour,$L_min,$L_sec,$meri,
    $days[$L_wday],$months[$L_mon],$L_mday,1900+$L_year
);




-- 
Cheers,
Robbie Hatley
Midway City, CA, USA
perl -le 'print "\154o\156e\167o\154f\100w\145ll\56c\157m"'
http://www.well.com/user/lonewolf/


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

Date: Mon, 26 Jan 2015 01:27:33 -0800
From: Robbie Hatley <see.my.sig@for.my.address>
Subject: Re: Why are these brackets necessary?
Message-Id: <2YCdncVG37vilVvJnZ2dnUVZ572dnZ2d@giganews.com>


On 1/26/2015 12:24 AM, Marius Gavrilescu wrote:

> Robbie Hatley <see.my.sig@for.my.address> writes:
>
> > But, that didn't work; gave errors on the range-operators.
> > So I found an example of a range used as a when test in a
> > Given in The Camel Book, which used brackets around the
> > range, like so:
> >     ...
> >     when ([1..11]) {...}
> >     ...
> >     when ([13..23]) {...}
> >     ...
> > And that worked. But I'm not sure why. What exactly are
> > those brackets doing there, anyway?
>
> See "Switch Statements" in perldoc perlsyn and "Smartmatch Operator" in
> perldoc perlop for the gory details.
>
> The "when" condition cannot be a list. It must be something from the
> table in "Smartmatch Operator". Relevant snippet:
>
>       Right operand is an ARRAY:
>
>       Left      Right      Description and pseudocode
>       ===============================================================
>       Any       ARRAY      smartmatch each ARRAY element[3]
>                      like: grep { Any ~~ $_ } ARRAY
>
> which means that if an array(ref) is supplied to when, it will match if
> $_ smartmatches any of the elements of the array(ref).

So basically, the [brackets] were being used to create a reference to an
array, and provided list context to the range operator so that it returns
the list of all integers in its range?

> However, smartmatch and given/when are experimental and their behaviour
> can change. You should generally use something like Switch::Plain instead.

I'll keep that in mind. In fact, I just changed the script so that it
no longer uses a given statement, but dumps the hour and AM/PM values
for times 0 through 23 into a 24-element array of 2-element arrays.
(See my other post of a few minutes ago.)


-- 
Cheers,
Robbie Hatley
Midway City, CA, USA
perl -le 'print "\154o\156e\167o\154f\100w\145ll\56c\157m"'
http://www.well.com/user/lonewolf/


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

Date: Mon, 26 Jan 2015 09:51:25 +0000
From: Justin C <justin.1410@purestblue.com>
Subject: Re: Why are these brackets necessary?
Message-Id: <t9fhpb-82e.ln1@zem.masonsmusic.co.uk>

On 2015-01-26, Marius Gavrilescu <marius@ieval.ro> wrote:
> --=-=-=
> Content-Type: text/plain
> Content-Transfer-Encoding: quoted-printable


Please don't do that.


   Justin.

-- 
Justin C, by the sea.


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

Date: Mon, 26 Jan 2015 09:17:40 +0000
From: Justin C <justin.1410@purestblue.com>
Subject: Re: Why are these brackets necessary?
Message-Id: <kadhpb-82e.ln1@zem.masonsmusic.co.uk>

On 2015-01-26, Robbie Hatley <see.my.sig@for.my.address> wrote:
> I was writing a script yesterday which gives both current
> GMT time (in 24Hr time scale) and current local time (AM/PM).
> To convert the hour and meridian (AM/PM indicator), I first
> tried code like this:
>
> given ($L_hour) {
>     when (0) {
>        $hour = 12;
>        $meri = "AM";
>     }
>     when (1..11) {
>        $hour = $L_hour;
>        $meri = "AM";
>     }
>     when (12) {
>        $hour = 12;
>        $meri = "PM";
>     }
>     when (13..23) {
>        $hour = $L_hour - 12;
>        $meri = "PM";
>     }
>     default {
>        $hour = 0;
>        $meri = "WTF???";
>     }
> }
>
> But, that didn't work; gave errors on the range-operators.
> So I found an example of a range used as a when test in a
> Given in The Camel Book, which used brackets around the
> range, like so:
>     ...
>     when ([1..11]) {...}
>     ...
>     when ([13..23]) {...}
>     ...
> And that worked. But I'm not sure why. What exactly are
> those brackets doing there, anyway?

They're creating a reference to an array. 

See Range Operators in perldoc perlop. You're evaluating the range 
operator in scalar context, it isn't doing what you think it is. By
creating a ref to an array I think you are getting the action you
require. However, I believe given/when are still experimental and
therefore their behaviour may change.

   Justin.

-- 
Justin C, by the sea.


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

Date: Mon, 26 Jan 2015 13:34:59 +0000
From: Rainer Weikusat <rweikusat@mobileactivedefense.com>
Subject: Re: Why are these brackets necessary?
Message-Id: <87a915ll6k.fsf@doppelsaurus.mobileactivedefense.com>

Robbie Hatley <see.my.sig@for.my.address> writes:
> On 1/26/2015 12:24 AM, Marius Gavrilescu wrote:
>
>> Robbie Hatley <see.my.sig@for.my.address> writes:

[...]

>> >     when ([1..11]) {...}
>> >     ...
>> >     when ([13..23]) {...}
>> >     ...
>> > And that worked. But I'm not sure why. What exactly are
>> > those brackets doing there, anyway?
>>
>> See "Switch Statements" in perldoc perlsyn and "Smartmatch Operator" in
>> perldoc perlop for the gory details.
>>
>> The "when" condition cannot be a list. It must be something from the
>> table in "Smartmatch Operator". Relevant snippet:
>>
>>       Right operand is an ARRAY:
>>
>>       Left      Right      Description and pseudocode
>>       ===============================================================
>>       Any       ARRAY      smartmatch each ARRAY element[3]
>>                      like: grep { Any ~~ $_ } ARRAY
>>
>> which means that if an array(ref) is supplied to when, it will match if
>> $_ smartmatches any of the elements of the array(ref).
>
> So basically, the [brackets] were being used to create a reference to an
> array, and provided list context to the range operator so that it returns
> the list of all integers in its range?

Not quite. [] is an anonymous array constructor (in this case) which
creates an anonymous array, possibly initialized with a list of values
appearing between [], and returns a reference to it. 

>> However, smartmatch and given/when are experimental and their behaviour
>> can change. You should generally use something like Switch::Plain instead.
>
> I'll keep that in mind.

It's not really true, however: The so-called 'smartmatch family of
features' were reclassified as 'experimental' with perl
5.18. Considering this, one obviously shouldn't use Perl at all as any
feature currently considered 'ready for general use' may become (or
again become) 'experimental' with some future perl release. Also,
'experimental' is mostly supposed to mean "if you consider this feature
useful, please consider becoming involved in its future development"
(obviously, someone needs to experiment with experimental features for
experimental to mean anyhting).


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

Date: Mon, 26 Jan 2015 16:26:49 +0000
From: Ben Bacarisse <ben.usenet@bsb.me.uk>
Subject: Re: Why are these brackets necessary?
Message-Id: <87ioftik3a.fsf@bsb.me.uk>

Robbie Hatley <see.my.sig@for.my.address> writes:

> On 1/25/2015 9:17 PM, $Bill wrote:
>
>> On 1/25/2015 19:55, Robbie Hatley wrote:
>> > I was writing a script yesterday which gives both current
>> > GMT time (in 24Hr time scale) and current local time (AM/PM).
>> > To convert the hour and meridian (AM/PM indicator), I first
>> > tried code like this:
>>
>> I'm still using 5.12 - not about to play with experimental features.  :)
>>
>> Why not just make a hash and then
>>      $hour = $hash{$L_hour}{'hour'};
>>      $meri = $hash{$L_hour}{'meri'} ;
>> and you're done ?
>
> Ah, that's a good idea. Or better, since $L_hour is always an integer
> in the range 0-23, and we're indexing on that, just use an array of
> refs to 2-element arrays. Lemme try that... Yes, works.  Yep, I like
> the following better than what I was doing with the given statement:
>
>
> #! /usr/bin/perl
> # "localtime.perl"
>
> my @months = qw(January   February  March     April
>                 May       June      July      August
>                 September October   November  December);
>
> my @days   = qw(Sunday    Monday    Tuesday   Wednesday
>                 Thursday  Friday    Saturday);
>
> my ($L_sec,  $L_min,  $L_hour,
>     $L_mday, $L_mon,  $L_year,
>     $L_wday, $L_yday, $L_isdst)
>     = localtime;
>
> my @hourmeri =
> (
>    [12, 'AM'], [ 1, 'AM'], [ 2, 'AM'], [ 3, 'AM'], [ 4, 'AM'], [ 5, 'AM'],
>    [ 6, 'AM'], [ 7, 'AM'], [ 8, 'AM'], [ 9, 'AM'], [10, 'AM'], [11, 'AM'],
>    [12, 'PM'], [ 1, 'PM'], [ 2, 'PM'], [ 3, 'PM'], [ 4, 'PM'], [ 5, 'PM'],
>    [ 6, 'PM'], [ 7, 'PM'], [ 8, 'PM'], [ 9, 'PM'], [10, 'PM'], [11, 'PM'],
> );
>
> my $hour = $hourmeri[$L_hour]->[0];
> my $meri = $hourmeri[$L_hour]->[1];
>
> printf
> (
>    "\nCurrent Local time is %02d:%02d:%02d%2s on %s %s %d, %d\n",
>    $hour,$L_min,$L_sec,$meri,
>    $days[$L_wday],$months[$L_mon],$L_mday,1900+$L_year
> );

You might also consider using

  $L_hour ? $L_hour - 12 : 12

and

  $L_hour >= 12 ? 'PM' : 'AM'

and the POSIX module lets you use strftime:

  strftime "Current Local time is %I:%M:%S%p on %A %B %d, %Y\n", localtime

-- 
Ben.


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

Date: Mon, 26 Jan 2015 23:49:20 -0800
From: Robbie Hatley <see.my.sig@for.my.address>
Subject: Re: Why are these brackets necessary?
Message-Id: <5dKdnfdXTf6c3lrJnZ2dnUVZ572dnZ2d@giganews.com>


On 01/26/2015 08:26 AM, Ben Bacarisse wrote:
 >    $L_hour ? $L_hour - 12 : 12

Close. :-) But not quite. That would work for 0 hours,
and for 13 hours through 23 hours, but not for 1..12:
  12 -11 -10  -9 -8  -7  -6  -5  -4  -3  -2  -1
  12   1   2   3  4   5   6   7   8   9  10  11

This could be done with if/elsif/else, like so:
if    (0 == $L_hour)   {$hour = 12;}
elsif ($L_hour <= 12)  {$hour = $L_hour;}
else                   {$hour = $L_hour-12;}

But wait, this is starting to look like a cyclic Abelian
group. It's screaming "use modular arithmetic" at 120dB.
But how? This is tricky because of the 12s. Hmmm. AH! Yes:

$hour=($L_hour-1)%12+1;

 > $L_hour >= 12 ? 'PM' : 'AM'

That works. But I wonder if even here, modular arithmetic
could be used? Hmmm. Not modulus, but integer division:

$meri=('AM','PM')[$L_hour/12];

 > and the POSIX module lets you use strftime:
 > strftime "Current Local time is %I:%M:%S%p on %A %B %d, %Y\n", localtime

Ah, a more automated approach. More efficient, but at the moment
I'm more interested in getting practice doing things in a more
manual way.


This is about as concise as I can see how to make this script,
using just the built-in features of Perl:


#! /usr/bin/perl
# "localtime.perl"

my @months = qw(January   February  March     April
                 May       June      July      August
                 September October   November  December);

my @days   = qw(Sunday    Monday    Tuesday   Wednesday
                 Thursday  Friday    Saturday);

my ($L_sec,   $L_min,   $L_hour,  $L_mday,  $L_mon,
     $L_year,  $L_wday,  $L_yday,  $L_isdst)
     = localtime;

my $hour  = ($L_hour-1)%12+1;
my $min   = $L_min;
my $sec   = $L_sec;
my $meri  = ('AM','PM')[$L_hour/12];
my $wday  = $days[$L_wday];
my $month = $months[$L_mon];
my $mday  = $L_mday;
my $year  = 1900+$L_year;

printf
(
    "\nCurrent Local time is %02d:%02d:%02d%2s on %s %s %d, %d\n",
    $hour,$min,$sec,$meri,$wday,$month,$mday,$year
);



-- 
Cheers,
Robbie Hatley
Midway City, CA, USA
perl -E 'print "\154o\156e\167o\154f\100w\145ll\56c\157m";'
https://www.facebook.com/robbie.hatley



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

Date: Tue, 27 Jan 2015 12:06:18 +0000
From: Ben Bacarisse <ben.usenet@bsb.me.uk>
Subject: Re: Why are these brackets necessary?
Message-Id: <874mrcfmx1.fsf@bsb.me.uk>

Robbie Hatley <see.my.sig@for.my.address> writes:

> On 01/26/2015 08:26 AM, Ben Bacarisse wrote:
>>    $L_hour ? $L_hour - 12 : 12
>
> Close. :-) But not quite. That would work for 0 hours,
> and for 13 hours through 23 hours, but not for 1..12:
>  12 -11 -10  -9 -8  -7  -6  -5  -4  -3  -2  -1
>  12   1   2   3  4   5   6   7   8   9  10  11

Yes, maybe

  $L_hour > 12 ? $L_hour - 12 : $L_hour || 12

I just wanted to propose the idea of an expression rather than an array
look-up.

> This could be done with if/elsif/else, like so:
> if    (0 == $L_hour)   {$hour = 12;}
> elsif ($L_hour <= 12)  {$hour = $L_hour;}
> else                   {$hour = $L_hour-12;}

That's rather wordy for my taste, but each to their own.

> But wait, this is starting to look like a cyclic Abelian
> group. It's screaming "use modular arithmetic" at 120dB.
> But how? This is tricky because of the 12s. Hmmm. AH! Yes:
>
> $hour=($L_hour-1)%12+1;

Yes, I thought of suggesting that, but not all languages choose the same
meaning for % with negative numbers so I've learned to be wary of it in
such situations (and I was too lazy to read the documentation).  But,
having now read it, I'd say it is arguably best avoided for negative
operands.  Perl defines % exactly as you want it *except* that a "use
integer" declaration will switch it to a less well-defined meaning,
which on my system turns out to be *not* the one you want!  Having code
that is fragile like that is a bit unnerving, but this may be a project
where it doesn't matter.

<snip>
-- 
Ben.


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

Date: Tue, 27 Jan 2015 13:50:27 +0000
From: Rainer Weikusat <rweikusat@mobileactivedefense.com>
Subject: Re: Why are these brackets necessary?
Message-Id: <877fw88h98.fsf@doppelsaurus.mobileactivedefense.com>

Robbie Hatley <see.my.sig@for.my.address> writes:
> On 01/26/2015 08:26 AM, Ben Bacarisse wrote:
>>    $L_hour ? $L_hour - 12 : 12

[...]

"FWIW",

> my $hour  = ($L_hour-1)%12+1;

This can also be expressed as

$L_hour % 12 || 12

> my $meri  = ('AM','PM')[$L_hour/12];

and this as

('AM', 'PM')[$L_hour > 12]

or

qw(AM PM)[$L_hour > 12]

or (what I'd prefer without having tested what's faster as it shouldn't
really matter here)

$L_hour > 12 ? 'PM' : 'AM;

As a curiosity,

$L_hour > 12 && 'PM' || 'AM'

works, too.


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

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


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