Re: tri-state flags

2001-12-05 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
Bart Lateur <[EMAIL PROTECTED]> wrote:
>I often use tri-state flags, with possible value true (1), false (0), or
>undetermined (undef).
>
>The question is: how do you test for one of the flags, in particular for
>0, without warnings?

Here's one way :)

use Data::Dumper;
$Data::Dumper::Terse = 1;
if (Dumper($flag) eq '0') ...



Re: tri-state flags

2001-12-09 Thread Yitzchak Scott-Thoennes

Bart Lateur <[EMAIL PROTECTED]> wrote:
>   grep { defined && !$_ } FLAG

To extend that, if you want to test for (state(s)) use (code):

state   code
undef   !defined FLAG
0   grep defined && !$_, scalar FLAG;
1   FLAG
undef,0 !FLAG
undef,1 grep !defined || $_, scalar FLAG;
0,1 defined FLAG
undef,0,1   1 :)

Yuck.



Re: Possible improvements for the next golf apocalypse

2001-12-11 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
Vladi Belperchinov-Shabanski <[EMAIL PROTECTED]> wrote:
>Piers Cawley wrote:
>> >> > 2. Tie-breaking rule
>> >> >
>> >> > I chose to break ties by rewarding the first to post.
>> >> > I suppose other ways are possible (e.g. reward the more
>> >> > efficient one) but they all seem a little artificial.
>> >>
>> >> This seems fair to me.  First in Best dressed.  I don't think that
>> >> efficiency and Golf should ever be mentioned in the same sentence :)
>> >
>> > `First wins' is not good IMO, perhaps some additional scoring like
>> > for example using non-average(usual) solution is better? this is
>> > arguable of cource but it is just an idea... of cource this won't
>> > be factor for different strokes count solutions...
>> 
>> The beauty of 'first in breaks the tie' is that it's objective. Which
>
>Depends very much of the free time you can use! It is *NOT* objective unless
>you get all players in a room and you give them timelimit!

Have each contestant emailed the holes upon request @ the contest web site,
recording the time the email was sent.

Then check how long it was before the answers were submitted.

Better yet, just report ties as ties.

I would prefer submissions be by plain email with files demarked by
\n===\n or some such.  The contest email would presumably send
a response form that just needed the actual code pasted into a reply.



Interactive golf hole

2002-01-08 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
Yanick <[EMAIL PROTECTED]> wrote:
>   You provide the course, I smack the balls.

I prefer (at least sometimes) to see golf worked out interactively, on the list.

Here's a hole:

A file has 0 or more fields on each line.
Fields are separated by 1 or more whitespace characters.
Leading and trailing whitespace should be ignored.
Comments (starting with # and continuing to the end of the line) should
be ignored.
A field may have surrounding double-quotes.  Such a field may contain # or
whitespace (but not ").  The surrounding quotes are themselves not part of
the field.  Any other use of a " has no special meaning (e.g.:
howdy, "partner# foo
is a line with two fields, 'howdy,' and '"partner').

Read the file and print the fields of each line separated by ':'.


I'll post my (far from optimal, I'm sure) solution in a little while.



Re: Interactive golf hole

2002-01-08 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
"Jeff 'japhy' Pinyan" <[EMAIL PROTECTED]> wrote:
>On Jan 8, Yitzchak Scott-Thoennes said:
>
>>I prefer (at least sometimes) to see golf worked out interactively, on
>>the list.
>
>I'm not sure I understand.  Shall I show my code?

Yes.

>  -n $\=$/;$,=':';print/("[^"]*"|[^\s#]+)\s*(?:#.*)?/g

Close.  I said: "The surrounding quotes are themselves not part of the
field", so the quotes should not get printed.  Also, I said: "Fields
are separated by 1 or more whitespace characters", so "x"x is one 4
character field, not two 1 character fields.



Re: Interactive golf hole

2002-01-08 Thread Yitzchak Scott-Thoennes

>On Tue, Jan 08, 2002 at 11:50:44AM -0800, Yitzchak Scott-Thoennes wrote:
>   -n $,=':';$\=$/;print grep$_,/\G\s*(?:"([^"]*)"(?:\s|$)|([^\s#]+))/g;
>   (but what a poor score it gives... :/ )

It gets worse:
While whitespace separates fields, the last field could have a comment next.
And "" is an empty field.  But I think the \G is unnecessary.

>-- 
>I must not fear. Fear is the mind-killer that brings total obliteration. 
>I will face my fear. I will permit it to pass over me and through me. And 
>when it is gone past I will turn the inner eye to see its path. Where the 
>fear has gone there will be nothing. Only I will remain. - Frank Herbert

-- 
I met this guy, and he looked like he might have been a hat check clerk
at an ice rink--which, in fact, he turned out to be. - Laurie Anderson



Re: Interactive golf hole

2002-01-08 Thread Yitzchak Scott-Thoennes

>> >-n $,=':';$\=$/;print grep$_,/\G\s*(?:"([^"]*)"(?:\s|$)|([^\s#]+))/g;
>> >(but what a poor score it gives... :/ )
>> 
>> It gets worse:
>> While whitespace separates fields, the last field could have a comment next.
>
>Ugh, missed that one too.  :)
>
>> And "" is an empty field.  But I think the \G is unnecessary.
>
>I think the \G is necessary because the regex doesn't explicitly match the
>comment.  The \G forces it to stop when it gets to the comment, rather than
>skipping over the # and matching more fields.

Oh, right.  Missed that.  Everything I've tried has actually matched
the comment.




Re: Interactive golf hole

2002-01-08 Thread Yitzchak Scott-Thoennes

Wesley Darlington <[EMAIL PROTECTED]> wrote:
>-p s/\s*("([^"]*)"|((\S*?)#.*)|(\S+))\s*/$2$4$5:/g,s/:+$/\n/

That's downright clever.  I think the approach could be a winner, but
as is it removes trailing empty fields:
x ""
becomes:
x
instead of:
x:



Re: Interactive golf hole

2002-01-08 Thread Yitzchak Scott-Thoennes

>Wesley Darlington <[EMAIL PROTECTED]> wrote:
>>-p s/\s*("([^"]*)"|((\S*?)#.*)|(\S+))\s*/$2$4$5:/g,s/:+$/\n/
>
>That's downright clever.  I think the approach could be a winner, but
>as is it removes trailing empty fields:
>x ""
>becomes:
>x
>instead of:
>x:

Now that someone has braved removing the quotes in the regex (which
I was hoping would happen) I'll post my solution that does it the
long way:

82:
-nl $,=":";print map/^"(.*)"$/?$1:$_,/\s*("[^"]*"(?=[\s#]|$)|[^\s#]+)\s*(?:#.*)?/g

This should be easily beatable.



Re: Interactive golf hole

2002-01-08 Thread Yitzchak Scott-Thoennes

Ronald J Kimball <[EMAIL PROTECTED]> wrote:
>Here's my current solution, at 64:
>
>-pl $_=join':',grep defined,/"([^"]*)"(?![^\s#])|([^\s#]+)|#.*/g
>
>Originally I had $_.0 instead of defined, but I realized that that skips
>empty fields, i.e. "".  Is there a shorter way to test for defined?

Not that I can think of.

>BTW, (?=\s|#|$) is shorter than (?=[\s#]|$).

So is (?![^\s#]).  That gets me to 62:

-pl s/\s*("([^"]*)"(?![^\s#])|([^\s#]+))\s*(#.*)?/$2$3:/g,chop



Re: Interactive golf hole

2002-01-09 Thread Yitzchak Scott-Thoennes

I wrote:
>Ronald J Kimball <[EMAIL PROTECTED]> wrote:
>>BTW, (?=\s|#|$) is shorter than (?=[\s#]|$).
>So is (?![^\s#]).

Which I just noticed you are using too.



Re: Interactive golf hole

2002-01-09 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] (Yitzchak Scott-Thoennes) wrote:
>Ronald J Kimball <[EMAIL PROTECTED]> wrote:
>>Here's my current solution, at 64:
>>
>>-pl $_=join':',grep defined,/"([^"]*)"(?![^\s#])|([^\s#]+)|#.*/g
>>
>>Originally I had $_.0 instead of defined, but I realized that that skips
>>empty fields, i.e. "".  Is there a shorter way to test for defined?
>
>Not that I can think of.
>
>>BTW, (?=\s|#|$) is shorter than (?=[\s#]|$).
>
>So is (?![^\s#]).  That gets me to 62:
>
>-pl s/\s*("([^"]*)"(?![^\s#])|([^\s#]+))\s*(#.*)?/$2$3:/g,chop

Which fails for lines with more than one character but no fields.
With no easy fix.  I think you've got the winner, Ronald.



Re: A perverse use of the glob function

2002-01-30 Thread Yitzchak Scott-Thoennes

Bart Lateur <[EMAIL PROTECTED]> wrote:
>If it should be just "fooa", then I'd like to mote that solutions based
>upon this trick would be disqualified, because they won't work on all
>reasonable systems.  :-)

perl56delta, aka perldelta for v5.6 & 5.6.1, says (n.b. this line = valid perl)

   File globbing implemented internally

   Perl now uses the File::Glob implementation of the glob()
   operator automatically.  This avoids using an external csh
   process and the problems associated with it.




Re: substitution question

2002-01-31 Thread Yitzchak Scott-Thoennes

In article <20020201025307.GC9474@blackrider>,
Michael G Schwern <[EMAIL PROTECTED]> wrote:
>
>$date = sprintf "%02d/%02d/%d", split '/', $date;

Perhaps slightly more efficient:
  $date = sprintf "%02d/%02d/%s", split '/', $date, 3;

But in some ways the regexp solutions are better since they'll leave
more malformed strings alone.



Re: substitution question

2002-02-01 Thread Yitzchak Scott-Thoennes

In article <20020201052621.GE9474@blackrider>,
Michael G Schwern <[EMAIL PROTECTED]> wrote:
>On Thu, Jan 31, 2002 at 08:10:00PM -0800, Yitzchak Scott-Thoennes wrote:
>> In article <20020201025307.GC9474@blackrider>,
>> Michael G Schwern <[EMAIL PROTECTED]> wrote:
>> >
>> >$date = sprintf "%02d/%02d/%d", split '/', $date;
>> 
>> Perhaps slightly more efficient:
>>   $date = sprintf "%02d/%02d/%s", split '/', $date, 3;
>
>You took the hood ornament off your car to reduce drag, didn't you.

It's also functionally different.  Otherwise I wouldn't have bothered.

>> But in some ways the regexp solutions are better since they'll leave
>> more malformed strings alone.
>
>Yay!  Silently failing code!

Better something that leaves $date = 'unexpected garbage' alone than
converts it to 00/00/0.  When 'unexpected garbage' turns up in the output
at some point, you have a better chance of tracking down where it came
from.

In my first programming job, one of the more experienced programmers
taught me "never check for an error condition you don't know how to
handle."  Words to live by. :)



Re: substitution question

2002-02-01 Thread Yitzchak Scott-Thoennes

"John W. Krahn" <[EMAIL PROTECTED]> wrote:
>On Friday 01 February 2002 02:26, Bart Lateur wrote:
>>
>>  $date =~ s{(\d+)/(\d+)/(\d+)}{sprintf '%02d/%02d/%d', $1, $2, $3}e;
>
>   $date = sprintf '%02d/%02d/%d', $date =~ m|(\d+)/(\d+)/(\d+)|;

That's very different.  Bart's doesn't translate if $date doesn't
match.  John's translates it to 00/00/0. Bart's leaves alone
extraneous leading and trailing characters.  John's strips them.

How about:

$date =~ s<^(\d+)/(\d+)/(-?\d+)\z>{ sprintf '%02d/%02d/%d', $1, $2, $3 }e;

I suspect Michael Schwern of suggesting the combination of s///e and
sprintf out of sarcasm, but s///e really does match the general
problem of if ($x =~ $re) { $x = f($x) } (or even
if ($x =~ $re) { $x = f($x) } else { error... } very well.

Though I really liked Ala's:

s|\b\d/|0$&|g

(translated into English: repeated B&D leads to emptiness.)



Re: TPR(0,1)...at last

2002-03-01 Thread Yitzchak Scott-Thoennes

References: <[EMAIL PROTECTED]>
Lines: 13

In article <[EMAIL PROTECTED]>,
Jerome Quelin <[EMAIL PROTECTED]> wrote:
>On Vendredi 1 Mars 2002 15:42, Philip Kendall wrote :
>> Do we have to deal with the case of the input having leading zeros?
>
>Sure. Excerpt from the rules:
>  You may assume that the first arg will be a properly formatted number
>  (matching the pattern /^\d+$/). Numbers will range from 0 to 2**32
>  (4294967296) inclusive.

If so, the term 'properly formatted' can be omitted without changing the
meaning.  The only possible extra meaning I see in the term 'properly
formatted' is that there will *not* be leading zeros.



Re: rethinking printf

2002-03-06 Thread Yitzchak Scott-Thoennes

In article ,
Rich Morin <[EMAIL PROTECTED]> wrote:
>Note that I'm suggesting a new function
>name because printf has a little-used capability that could conflict with
>my proposed syntax:
>
>   "The format string is reused as often as necessary
>to satisfy the arguments."

Where did you get that?  Not true for Perl or C.



Re: rethinking printf

2002-03-06 Thread Yitzchak Scott-Thoennes

In article <p05100304b8aca0caa3ca@[192.168.254.205]>,
Rich Morin <[EMAIL PROTECTED]> wrote:
>At 5:27 PM -0800 3/6/02, Yitzchak Scott-Thoennes wrote:
>>>"The format string is reused as often as necessary
>>> to satisfy the arguments."
>>
>>Where did you get that?  Not true for Perl or C.
>
>Apparently, when I did a "man printf", I got the one in FreeBSD's Section 1:
>>   The format string is reused as often as necessary to satisfy the
>>   arguments.  Any extra format specifications are evaluated with zero or
>>   the null string.

Thats funky.

POSIX (IEEE 1003.1-2001) says:
If the format is exhausted while arguments remain, the excess
arguments shall be evaluated but are otherwise ignored.

And C99 (ISO 9899-1999 section 7.19.6.1) says:
If the format is exhausted while arguments remain, the excess
arguments are evaluated (as always) but are otherwise ignored.

Does it in fact reuse the format on your system?

>I also think Fortran FORMAT statements acted this way, but it's been
>far too long for me to remember for sure...  In any case, it seems
>that it isn't a problem...

Yes, Fortran mostly works this way.



Re: rethinking printf

2002-03-07 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
=?koi8-r?B?RG1pdHJ5IEtvaG1hbnl1ayDkzcnU0snKIOvPyM3BzsDL?= <[EMAIL PROTECTED]> wrote:
>On Wed, Mar 06, 2002 at 08:56:18PM -0800, Yitzchak Scott-Thoennes wrote:
>> >Apparently, when I did a "man printf", I got the one in FreeBSD's Section 1:
>> >>   The format string is reused as often as necessary to satisfy the
>> >>   arguments.  Any extra format specifications are evaluated with zero or
>> >>   the null string.
>> 
>> Thats funky.
>
>   this is section *1* manual, for commands, right?  

Whoops.  Didn't notice the section number, my apologies.

>   It's possible that printf *program* does that, but that's really weird.
>
>   (yes, indeed: printf(1) FreeBSD 3.5, Linux 2.2.14, and SunOS 5.8 aka Solaris 8 
>are
>   documented and work this way.)
>
>> POSIX (IEEE 1003.1-2001) says:
>> If the format is exhausted while arguments remain, the excess
>> arguments shall be evaluated but are otherwise ignored.

Above is obviously for printf(3).  For printf(1) it indeed says:
  9. The format operand shall be reused as often as necessary to
 satisfy the argument operands. Any extra c or s conversion
 specifiers shall be evaluated as if a null string argument were
 supplied; other extra conversion specifications shall be evaluated
 as if a zero argument were supplied. If the format operand
 contains no conversion specifications and argument operands are
 present, the results are unspecified.



Re: rethinking printf

2002-03-10 Thread Yitzchak Scott-Thoennes

 <[EMAIL PROTECTED]> <[EMAIL PROTECTED]>
 <[EMAIL PROTECTED]>
Lines: 17

In article <[EMAIL PROTECTED]>,
Uri Guttman <[EMAIL PROTECTED]> wrote:

>i disagree. but we shall see if larry is listening to this thread and
>will back away from hash interpolation or take some of our suggestions
>that make it work without killing format strings. i hate to see a
>special call or wierd syntax for that. my qn (or qf) suggestion seems to
>have some backing and it is clean and unobtrusive.

If you are going to make a special q form for sprintf strings, don't
make it just skip hash interpolation.  Make it treat [@$%] all as
literals and only process backslashed thingies (including \qq of
course).  If you want to interpolate a $foo in an printf format, use
%s.

The idea of interpolating %foo{bar} but not %foo seems unnecessarily
complicating.



Re: rethinking printf

2002-03-10 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
"Brent Dax" <[EMAIL PROTECTED]> wrote:
>
>There's only a clash if you double-quote the format string anyway, which
>is a rare thing to need to do at all.

I'd expect that a hefty percentage of format strings have a \n.




Re: Golf spectators

2002-03-18 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
Dave Hoover <[EMAIL PROTECTED]> wrote:
>Piers wrote:
>> So, how about having some way of letting spectators see the
>> entries.
>
>I can't think of a good way to do this *during* the tournament.  
>I know if I was golfing, there's no way I could resist looking at 
>the solutions.

So set up a list that all solutions go to upon submission.
No players would subscribe to such a list, and no archive
would be available.



Re: Golf spectators

2002-03-24 Thread Yitzchak Scott-Thoennes

In article <Pine.LNX.3.96.1020319100459.13630A-10@gentoo>,
Stephen Turner <[EMAIL PROTECTED]> wrote:
>On Mon, 18 Mar 2002, Yitzchak Scott-Thoennes wrote:
>> 
>> So set up a list that all solutions go to upon submission.
>> No players would subscribe to such a list, and no archive
>> would be available.
>> 
>
>You only have one email address?

Five.  But do you expect people to cheat?  As is, what's to prevent
everyone but the leader from quietly exchanging their solutions in an
attempt to best him/her?



Re: First differing char in two strings

2002-04-11 Thread Yitzchak Scott-Thoennes

>>  ($a ^ $b) =~ /^(\0*)/ && length $1
>
>Whether they give the same value depends on the values of $a and $b.  Try
>it with $a = 'abcdef' and $b = 'abCdef', for example.

To work with any $a and $b, you should play it safe and say: "$a"^"$b".
Otherwise the used-in-numeric-context gremlins will eat your code.



Re: Whitespace and Blocks

2002-04-18 Thread Yitzchak Scott-Thoennes

I'd just like to congratulate everyone on maintaining civility in what
could have been a very incendiary thread.  (I did see one ad hominem,
but that's pretty good for 50 posts and counting.)



Re: shortest test for truth & false assignment

2002-05-22 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
Scott Wiersdorf <[EMAIL PROTECTED]> wrote:
>$a && $a-- && do {
>do_something();
>   ...
>}
>
>Two questions: a) can it be shortened to fewer characters? and b) is
>there another way to do it better in general?

This is longer (not to mention demented) but should work with any true value:

(($a)=$a?():$a)|| do { ... }



Re: shortest test for truth & false assignment

2002-05-22 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
Ronald J Kimball <[EMAIL PROTECTED]> wrote:
>> > if ($a=~tr/.[^0]+/0/c) { do_something(); }
>Actually, it translates every character that is *not* one of '.[^0]+' into '0'.

Which means it does work, with slightly altered true/false semantics
than are usual for perl.  (true means contains non-^,+,],[,.,0
character(s)).

Even the simplified:

if ($a=~y/0/0/c) { ... } 

has e.g. "00" as false when by usual perl semantics it is true.

You could just as well say:

if ($a=~y/x/x/c) { ... }

and have true mean contains non-x characters, false mean empty or only x's.



Re: Reading Huge Files into Memory

2002-06-11 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
Michael G Schwern <[EMAIL PROTECTED]> wrote:
>
>so length() is very cheap.  Unlike strlen() in C, it doesn't have to walk
>the string looking for a null byte.

Unless it is flagged as utf8, in which case it does have to walk the
string to count the length in *characters*.
>
>> If your interested, there's a few oddities I discovered en route too:
>> 1) The code: 
>>  next if $seen{$_}; $seen{$_}=1;
>> according to my benchmaring is faster than: 
>>  unless ($seen{$_}++)  {...}
>> even though the former looks up $seen{$_} twice, and ++ is a pretty trivial
>> operator. Its not where I'd have put my money.
>
>Here's what I get on Linux.

Michael, your benchmark is flawed.  If that ... above is more than one
statement, the { } with the unless version costs a lot more.
Nevertheless, with s/delete \$hash{foo}/$&; $&/ on the benchmark, I still
see unless slightly faster:

~ $perl5.8.0 bench.pl
Benchmark: running control, next, unless for at least 3 CPU seconds...
   control:  4 wallclock secs ( 4.38 usr +  0.00 sys =  4.38 CPU) @ 642700.98/s 
(n=2815673)
  next:  3 wallclock secs ( 3.13 usr +  0.00 sys =  3.13 CPU) @ 121639.30/s 
(n=380731)
unless:  4 wallclock secs ( 3.06 usr +  0.00 sys =  3.06 CPU) @ 214766.64/s 
(n=658045)
Ratenext  unless control
next121639/s  ---43%-81%
unless  214767/s 77%  ---67%
control 642701/s428%199%  --
~ $perl5.8.0 corrected_bench.pl
Benchmark: running control, next, unless for at least 3 CPU seconds...
   control:  4 wallclock secs ( 3.07 usr +  0.00 sys =  3.07 CPU) @ 631012.71/s 
(n=1936578)
  next:  3 wallclock secs ( 3.16 usr +  0.00 sys =  3.16 CPU) @ 109031.61/s 
(n=344976)
unless:  3 wallclock secs ( 3.12 usr +  0.00 sys =  3.12 CPU) @ 136536.09/s 
(n=425583)
Ratenext  unless control
next109032/s  ---20%-83%
unless  136536/s 25%  ---78%
control 631013/s479%362%  --



Re: perl5.6.1 oddity?

2002-06-14 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>, Chris Dolan <[EMAIL PROTECTED]> wrote:
>can someone explain why =
>does not warn?  Is it because (quoting perlop)
>
> $a += 2; is equivalent to $a = $a + 2; although without
> duplicating any side effects that dereferencing the lvalue
> might trigger
>
>and the warn is considered a side effect?  Or is it just a kluge to
>support someone developer's personal preferences?

The latter.  The following operators intentionally suppress the warning if
the left (or only) operand is undef:
++ and -- (both pre- and post- variants), |= and ^= (both string and numeric),
&&=, ||=, +=, -=, and .=.

This is considered a Good Thing(TM).  I thought this was documented
somewhere (other than t/op/assignwarn.t :) but can't find it now.

>Is it possible to enable warnings for this case in 5.8?

Too late, I'm afraid.



Re: puzzling greed

2002-06-14 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
Peter Scott <[EMAIL PROTECTED]> wrote:
>..+? Match at least one character that isn't a newline,

I assume you meant '.+?'.  Avoid putting periods at the beginning of
a line since many mail agents do s/^\./../m.




Re: Maybe-useful subroutine (BETTER!)

2002-07-01 Thread Yitzchak Scott-Thoennes

Yet Another *::Util Plug:

Scalar::Util::reftype finds the underlying type even for objects.
(Unfortunately for non-refs it returns undef instead of '' as the
builtin ref does.)

In article <[EMAIL PROTECTED]>,
Abigail <[EMAIL PROTECTED]> wrote:
>#!/usr/bin/perl -w
>
>use strict;
>use warnings 'all';

use Scalar::Util 'reftype';

>sub rotate {

no integer;  # I like to explictly say it per sub when I'm depending on it

>return () unless   $_ [1];
>die "Not an array ref" unless "ARRAY" eq ref $_ [1];

die "Not an array ref" unless ref $_ [1] && "ARRAY" eq reftype $_ [1];

>return [] unless @{$_ [1]};
>my $l = $_ [0] % @{$_ [1]};
>[@{$_ [1]} [$l .. $#{$_ [1]}, 0 .. $l - 1]]
>}
>  
>my $array = ['A' .. 'E'];

bless $array; # simulate rotating an array-based object

>for my $r (-15 .. 15) {
>printf "Rotate %3d: @{rotate $r, $array}\n", $r;
>}

I didn't think that was obfuscated.
How about this:

sub rotate {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]%@
{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{$_
[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]}



Re: Maybe-useful subroutine (BETTER!)

2002-07-01 Thread Yitzchak Scott-Thoennes

In article <[EMAIL PROTECTED]>,
"sara starre" <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] (Yitzchak Scott-Thoennes) wrote:
>
>>I didn't think that was obfuscated.
>>How about this:
>
>sub rotate {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]%@
>{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{$_
>[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]}
>
>
>  **
>
>I think my cerebral cortex just core-dumped! Ow my head hurts L)

I don't see why, seems fairly straightforward...  :)
Only really strange part is "!!$^^^!$^^", where it doesn't seem like
that should be a valid variable name.  I think my favorite part
was "!$..!!$."



Re: correctly rebuilding a whitespace-split string

2002-10-14 Thread Yitzchak Scott-Thoennes

On Mon, 14 Oct 2002 20:19:10 -0400 (EDT), [EMAIL PROTECTED] wrote:
>
>Someone have a more "perlish", elegant, or just plain faster way of doing
>something like this: split a string on white space, pop off the last 4
>fields (perhaps to be used elsewhere), and then "rebuild" the original
>string with the correct amount of intervening whitespace.

(@bollocks[3,2,1,0], $want) = map scalar reverse, split ' ', reverse($in), 5



Re: correctly rebuilding a whitespace-split string

2002-10-14 Thread Yitzchak Scott-Thoennes

On Tue, 15 Oct 2002 13:17:09 +1000, [EMAIL PROTECTED] wrote:
>my ($want,@bollocks) = /(.*?)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*$/g;

g?



Re: ~9M lines of data

2002-10-25 Thread Yitzchak Scott-Thoennes
On Fri, 25 Oct 2002 11:11:53 -0400, [EMAIL PROTECTED] wrote:
>Vladi Belperchinov-Shabanski <[EMAIL PROTECTED]> writes:
>=>#!/usr/bin/perl -n
>=>$c = 50 if /CREATE TABLE/;
>=>print if $c and $c--;

The solution above works even if CREATE TABLE is repeated within 50 lines,
the solution below does not.

>This seems to work:
>
>|| perl -ne 'print if /CREATE TABLE/ .. (++$c > 50)' nine-megs.txt



Re: Function parameter passing

2002-11-25 Thread Yitzchak Scott-Thoennes
On Mon, 25 Nov 2002 11:34:23 + (GMT), [EMAIL PROTECTED] wrote:
>>  $i = 20;
>>  my($x, $y, $z) = ($i++, $i, $i++);
>
>Now, it appears that perl's evaluation order is accident rather than
>design - so you SHOULD NOT rely on it.  Avoid causing side-effects on
>variables you use more than once... including the multiple use of shift
>in assignment.

This isn't an issue of evaluation order.  In the example above, perl
evaluates first $i++, then $i, then $i++, placing the results in a
list.  Then the assignment is done.  The reason $y becomes 22 is that
the *variable* $i is in the list (by reference, if you will), not the
*value* of $i.  Only when the assignment is done is the value
accessed.

Keep in mind that perl passes parameters by reference, and almost all
operands act just like subroutine parameters.  If you have:

sub aassign{ print "\$_[$_] is $_[$_]\n" for 0..$#_ }
$i = 20;
aassign($i++, $i, $i++)

you get:

$_[0] is 20
$_[1] is 22
$_[2] is 21



Re: More fun with with lists and ++

2002-11-25 Thread Yitzchak Scott-Thoennes
On Mon, 25 Nov 2002 21:16:10 -,
[EMAIL PROTECTED] wrote:
>
>Can anyone explain why these print different output?
>
>my ($x,$y);
>print $x++ , ++$x , $x++ ,"\n";  # prints 032  
>print $y++ . ++$y . $y++ ,"\n";  # prints 022 

$x++ and ++$x are fundamentally different beasts.
$x++ increments $x after creating a temp var to return $x's orig value.
++$x increments and returns the variable $x (*not* its value).

The first line is equivalent to:
$x = 3;
print(0, $x, 2);

The second is:
print(($y++ . ++$y) . $y++)

where ($y++ . ++$y) is like:
$y = 2; "0"."$y"

>I was going to suggest that someone that the ++prefix was bugged only over
>the "," operator until I saw this:
>
>my ($x,$y);
>print ++$x , ++$x , ++$x , ++$x , ++$x , ++$x ,"\n"; # prints 66
>print ++$y . ++$y . ++$y . ++$y . ++$y . ++$y ,"\n"; # prints 223456 (and
>not 123456!)
>
>Shouldn't the super-high precedence of ++ prevent there from being any
>distinction between the "." and the "," operator?

The first places 6 instances of $x on the stack, incrementing it 6 times as
a side effect.  When it is printed, it prints 66.

For the second, perhaps parentheses make it clearer:
   print((++$y . ++$y) . ++$y) . ++$y) . ++$y) . ++$y))

The first . places two instances of $y on the stack, also incrementing
it twice.  These are then concatenated as "22".  Then $y is
alternately incremented and concatenated four more times, giving
223456.



Re: Metaprogramming

2002-12-15 Thread Yitzchak Scott-Thoennes
On Sat, 14 Dec 2002 19:09:43 -0500, [EMAIL PROTECTED] wrote:
>On 14 Dec 2002, at 21:45, Rafael Garcia-Suarez wrote:
>
>> What do you expect B::Deparse::coderef2text to do here ? Output
>> something equivalent to { 42 + shift } ? or produce an error ("can't
>> deparse a closure without complete lexical context") ?
>
>In fact, unless I'm misunderstanding how the closure works, "$constant"
>is exactly correct and '42' would be incorrect...  Isn't it the case that
>the subroutine could have as easily done:
>   sub { $constant++ + shift; }
>The fact that you *call* it "$constant" doesn't make it a constant, and
>the fact that it is a closure and its name is out of scope doesn't make
>it read only.  So I think that the deparse is as close to perfect as it
>could be, isn't it?

Yes.  It is the responsibility of the caller of coderef2text to make
sure any eval of the code occurs in the same lexical context as the
original code (if desired).  Given that this is, in general, possible,
Deparse should produce neither 42+shift or an error.

I certainly can't see any point in conditionally giving an error based
on where the "coderef2text" aktescalp e.



Re: Metaprogramming

2002-12-15 Thread Yitzchak Scott-Thoennes
On Sat, 14 Dec 2002 21:09:38 -0800, [EMAIL PROTECTED] wrote:
>I certainly can't see any point in conditionally giving an error based
>on where the "coderef2text" aktescalp e.
 ^^^
anagram of "takes place"



Re: Converting a textfile-like string to an array and back

2003-02-07 Thread Yitzchak Scott-Thoennes
On Fri, 7 Feb 2003 15:05:47 +0100, [EMAIL PROTECTED] wrote:
>Not if the last line did not end with a record separator.
>His example data did, but other data might not.

In general, I'm all in favor of coding charitably toward files w/o a
trailing newline.  Here, however, the OP wants to convert data between
two forms, one of which doesn't have any way to store a 'final newline
missing' flag.  Hence, this problem can't have a solution that allows
that distinction.  The best that can be done is to make allowances for
the situation on the scalar->list side only, e.g. (untested):
chomp(my $tmp=$x); my @lines=split /\n/,$tmp,-1
instead of:
my @lines=split /\n/,$tmp,-1; pop(@lines);



Re: Converting a textfile-like string to an array and back

2003-02-08 Thread Yitzchak Scott-Thoennes
On Sun, 9 Feb 2003 12:34:38 +1100 (EST), [EMAIL PROTECTED] wrote:
>Yitzchak Scott-Thoennes  wrote:
>> chomp(my $tmp=$x); my @lines=split /\n/,$tmp,-1
>
>This one fails for the case $x = "\n"; @lines should contain one
>empty element, but the code above contains none.

Sigh.  I'd call that a bug if someone hadn't gone to the trouble to
test for it and document it.  (Indeed, I see a bug report out there:
#6653, was 20010327.008.) So do something like:

my @lines;
chomp(my $tmp=$x);
@lines = split /\n/,$tmp,-1 or @lines=""



Re: Converting a textfile-like string to an array and back

2003-02-08 Thread Yitzchak Scott-Thoennes
On Sun, 9 Feb 2003 14:34:07 +1100 (EST), [EMAIL PROTECTED] wrote:
>sub a2 { my $y = ""; $y .= $_ . "\n" for @lines }

The ="" is optional. my $x; $x.="foo" intentionally doesn't warn.



Re: Converting a textfile-like string to an array and back

2003-02-10 Thread Yitzchak Scott-Thoennes
On Mon, 10 Feb 2003 11:09:25 +1100 (EST), [EMAIL PROTECTED] wrote:
>Yitzchak Scott-Thoennes wrote:
>> Sigh.  I'd call that a bug if someone hadn't gone to the trouble to
>> test for it and document it.  (Indeed, I see a bug report out there:
>> #6653, was 20010327.008.) So do something like:
>> 
>> my @lines;
>> chomp(my $tmp=$x);
>> @lines = split /\n/,$tmp,-1 or @lines="" 
>
>This one fails for $x = "" producing a @lines with one element.

Only if you say $x eq "" means no lines instead of one empty line missing
its "\n" :)



Re: Converting a textfile-like string to an array and back

2003-02-10 Thread Yitzchak Scott-Thoennes
On Mon, 10 Feb 2003 23:44:14 -0500, [EMAIL PROTECTED] wrote:
>Yitzchak Scott-Thoennes <[EMAIL PROTECTED]> wrote:
>
>> Only if you say $x eq "" means no lines instead of one empty
>> line missing its "\n" :)
>
>Well, the subject line does say "textfile-like", and a 0-byte 
>text file has no lines, not one empty line.

Apparently you missed the smiley.

In any case, a 0-line file is identical to a 1-line file where the
one line is empty and the "\n" is missing.

Similarly, "abc\n" is either a 1-line file, or a 2-line file where the
second line is empty and "\n" is missing.  :) :) :)



Re: my if?

2003-07-01 Thread Yitzchak Scott-Thoennes
On Tue, 1 Jul 2003 10:30:34 -0400, [EMAIL PROTECTED] wrote:
>On Tue, Jul 01, 2003 at 05:15:09PM +0300, Vladi Belperchinov-Shabanski wrote:
>>   my $id = 1 if $_ == 3;
>This was an accidental feature that is now kept for backwards
>compatibility, because some programmers have used it to create static
>variables.  It's best to avoid it, however.

As others have observed, it doesn't really make static variables since
a new pad will be used for each level of recursion.  I also think that
with multiple ithreads, each thread will use a different pad.

I don't think it was kept for backwards compatibility; I think it just
would be very difficult to make it work otherwise, though Dave
Mitchell and Gurusamy Sarathy have discussed[1] doing so (with,
surprisingly, no objections).  The problem with keeping it is that
people keep stumbling across it accidentally.

[1] http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2003-03/msg00019.html


Re: qw(l i s t) vs (l, i, s, t)

2003-07-22 Thread Yitzchak Scott-Thoennes
On Tue, 22 Jul 2003 03:48:53 +0200, [EMAIL PROTECTED] wrote:
>
>Could someone please explain what is happening here?
>I came across it, and had a hard time trying to figure out what was 
>going on.

When you use an array in scalar context (e.g. scalar(@ARGV)==foo, or even
just @ARGV==foo), it gives the number of elements in the array (either
2 or 3 in your examples).

When you use a comma-operator in scalar context (e.g. (2,3)) it throws
away the left operand and returns the right one.

qw() should act just like a comma'd list, so scalar(qw(2 3)) should be
3.  You aren't seeing this, so I suspect you to be using an extremely
old version of perl where qw() didn't work as well.  If you upgrade to
5.005_55 or higher you should see qw() acting better.


Re: A little arithmetic puzzle

2003-08-14 Thread Yitzchak Scott-Thoennes
On Thu, Aug 14, 2003 at 11:02:19AM +0100, Jonathan E. Paton wrote:
> Easy, the fastest method is to use stack based notation (RPN).  This
> completely avoids the need for those pesky brackets.  The stack is
> arranged into each of the permutations, and then the operators applied
> in each permutation.  There is only 24 permutations of the numbers, and
> 64 permutations of the operators, combined there is 1536 different
> expressions.  We need to select only those evaluating to 21.

Each of those 1536 expressions has 5 variants corresponding to
the five different ways of parenthesizing the non-RPN version.
You only seem to check 1 of the 5.

Where n is one of the numbers and op is one of the ops, you
need to try:

RPN non-RPN
n n n n op op opn op (n op (n op n))
n n n op n op opn op ((n op n) op n)
n n n op op n op(n op (n op n)) op n
n n op n n op op(n op n) op (n op n)
n n op n op n op((n op n) op n) op n

Here's my try.  Note that special handling may be needed to avoid an
answer for which the computer gets 20.9 or similar, when
the true answer would be 21.  This could involve using something like
Math::BigRat instead of floating point math, or checking for an answer
within some small margin of 21 (which can be done somewhat
automatically by setting the deprecated $# var to the appropriate
precision and stringifying the number).  On my system, fudging this
way isn't needed for this problem, but not all the world is 64-bit
IEEE.

#!perl -l
use strict;
# $# = "%.6g"; # uncomment this if needed for your system's floating point math
use warnings;

# build series of ops to use (4*4*4)
my @ops = [];
@ops = map {["+",@$_],["-",@$_],["/",@$_],["*",@$_]} @ops for 1..3;

# apply each possible precedence (4*4*4*5)
my @templates = map {
sprintf("%%d %s (%%d %s (%%d %s %%d)) eq 21", @$_),
sprintf("%%d %s ((%%d %s %%d) %s %%d) eq 21", @$_),
sprintf("(%%d %s (%%d %s %%d)) %s %%d eq 21", @$_),
sprintf("(%%d %s %%d) %s (%%d %s %%d) eq 21", @$_),
sprintf("((%%d %s %%d) %s %%d) %s %%d eq 21", @$_)} @ops;

# and try each permutation of numbers (4*4*4*5*24)
for my $nums (permute(1,5,6,7)) {
eval(sprintf $_, @$nums) and printf("$_\n", @$nums) for @templates;
}

sub permute {
@_ <= 1 ? (wantarray ? [EMAIL PROTECTED] : 1) : do {
my @ret;
for my $i (0..$#_) {
push @ret, grep push(@$_, $_[$i]), permute(@_[0..$i-1,$i+1..$#_])
}
@ret;
}
}


perl syntax oddity

2003-09-18 Thread Yitzchak Scott-Thoennes
Can anyone give a justification why this should work as it does (or a
reasonable use):

$ perl -wle'sub getaglob {*loopvar} for ${&getaglob} (qw/the owl and the pussyc
at/) { print $loopvar }'
the
owl
and
the
pussycat

I was just browsing perly.y and saw that C< for $ BLOCK (... > is
(perhaps accidentally) valid syntax.  BLOCK is expected to return a
glob or globref.


Re: perl syntax oddity

2003-09-18 Thread Yitzchak Scott-Thoennes
On Thu, Sep 18, 2003 at 12:07:16PM +0300, Ilmari Karonen <[EMAIL PROTECTED]> wrote:
> I guess it's because for() localizes the variable it's iterating over, 
> and needs the glob for that.  Oddly enough, however, local() does not 
> accept a glob that way:

for $x () does a more complete localization than local($x) does:

use Tie::Scalar;
tie $x, "Tie::StdScalar";
sub checktie { print '$x is ', (tied($x)?'':'not '), "tied in $_[0]\n" }
for $x (1) { checktie('for') }
{ local $x; checktie('local($x)') }
{ local *x; checktie('local(*x)') }

>   sub getaglob {*foo}
>   $foo = "pong\n";
>   for ${&getaglob} ("ping ") { print $foo }
>   print $foo;
> 
> works, printing "ping pong", while:
> 
>   sub getaglob {*foo}
>   $foo = "pong\n";
>   { local ${&getaglob} = "ping "; print $foo }
>   print $foo;
> 
> fails with "Can't localize through a reference"!

This error seems to be removed in 5.8.1 and it works there (though the
error entry was erroneously left in perldiag).

But this prints "pingping":

sub foo:lvalue { $foo }
$foo = " pong\n";
{ local &foo; print $foo="ping" }
print $foo;


Re: perl syntax oddity

2003-09-19 Thread Yitzchak Scott-Thoennes
On Thu, Sep 18, 2003 at 07:53:39PM -, Rafael Garcia-Suarez <[EMAIL PROTECTED]> 
wrote:
> Yitzchak Scott-Thoennes wrote in perl.fwp :
> >> 
> >>   sub getaglob {*foo}
> >>   $foo = "pong\n";
> >>   { local ${&getaglob} = "ping "; print $foo }
> >>   print $foo;
> >> 
> >> fails with "Can't localize through a reference"!
> > 
> > This error seems to be removed in 5.8.1 and it works there (though the
> > error entry was erroneously left in perldiag).
> 
> perldiag is still correct, because this error was only removed in some
> cases.  Perl 5.8.1 allows localization through a symbolic reference, but
> not a hard one :
> 
> $ bleadperl -le '$x="a";local $$x=2;print$a,$$x'
> 22
> 
> $ bleadperl -le '$x=\"a";local $$x=2;print$$x'
> Can't localize through a reference at -e line 1.

Sorry for casting aspersions while leaping to conclusions...I grepped
*.c and saw it there for 5.6.2 but not 5.8.1.  I forgot to check *.h.

So is it unintentional that you can localize through an expression
resulting in a glob?


Re: Comparing items from multiple files

2003-11-20 Thread Yitzchak Scott-Thoennes
On Wed, Nov 19, 2003 at 10:02:34PM -, Peter Scott <[EMAIL PROTECTED]> wrote:
> Problem: multiple files containing essentially identical
> reports which I want to compare.  'diff' isn't the answer;
> in this case each file contains a bunch of stuff I'm not
> interested in that can change; I just want to get an element
> of each one and say which of the other files don't contain that
> element.

I would do it more like this:

use warnings;
use strict;

sub check_re { eval { qr/${\shift}/ } || return }

my $regex = "(".shift().")";
check_re($regex) or die "invalid regex: $regex\n";

my %files;
my %data;

while (<>) {
   ++$files{$ARGV};
   next unless /$regex/;
   ++$data{$+}{$ARGV};
}

my @files = sort keys %files;

for my $value (sort keys %data) {
   if (keys %{$data{$value}} != @files) {
  printf "In %s but not in %s: %s\n",
  join(", ",keys %{$data{$value}}),
  join(", ",grep !exists $data{$value}{$_}, @files),
 $value;
   }
}


Re: fractional cents

2004-04-20 Thread Yitzchak Scott-Thoennes
On Mon, Apr 19, 2004 at 11:22:21PM +0200, "A. Pagaltzis" <[EMAIL PROTECTED]> wrote:
> Because I think
> 
> chop if /\.\d\d0\z/;
> 
> is clearer to read than
> 
> s/(?<=\.\d\d)0\z//;
> 
> or even (yuck!)
> 
> s/(\.\d\d)0\z/$1/;

do{local $/=0;chomp}


Re: mini-golf: first differing position

2004-04-20 Thread Yitzchak Scott-Thoennes
On Tue, Apr 20, 2004 at 09:59:46PM -0400, Bernie Cosell <[EMAIL PROTECTED]> wrote:
> On 20 Apr 2004 at 20:48, Craig S. Cottingham wrote:
> > I couldn't get that to work.
> 
> Really?  I cleaned it up a bit and it seems to work fine:
> 
> sub diff
> {   my $diff = $_[0] ^ $_[1];
> my ($len) = $diff =~ /^([\0]*)[^\0]/ ;
> return undef if not defined $len ;
> return length $len;
> }

Perhaps he used numbers instead of strings.  It's a good idea to always
force the bitops to behave in the mode you want:
   my $diff = "$_[0]" ^ "$_[1]";


Re: AW: mini-golf: first differing position

2004-04-21 Thread Yitzchak Scott-Thoennes
On Wed, Apr 21, 2004 at 09:44:54AM +0200, Xavier Noria <[EMAIL PROTECTED]> wrote:
> Good. With a little modification we get 26 if this is right:
>
> $_=$x^$y;$n=$-[0]if/[^\0]/

$x = "abc"; $y = "abc\0\0\0"; gives undef instead of the required 3

On Wed, Apr 21, 2004 at 07:48:57AM +0200, Xavier Noria <[EMAIL PROTECTED]> wrote:
>
> {$x ne$y&&$x=~/./sg&$y=~/\G$&/g&&redo;$n=$-[0]}

Needs a \Q after the \G. (Consider $x = "a.c" and $y = "abcdef" or
$x = "a+c" and $y = "a+cd".)


Re: xor of unicode strings

2004-04-21 Thread Yitzchak Scott-Thoennes
On Wed, 21 Apr 2004, Bernie Cosell wrote:

> I'm not sure if this is 'fun', but it might be at least curious: I don't
> have a UTF-8 system handy to try, but I'm wondering: what happens with
> the string-xor operator on UTF-8 strings.  It obviously cannot work byte-
> by-byte, but it seems like it is going to be a bit tricky figuring out
> what you get when you xor a 1 byte character with a 2-byte one [I guess
> what it would have to do to be 'correct' would be to convert the UTF to
> "real Unicode", XOR the 32-bit "characters" together, and then compress
> that resulting "character" back to UTF-8...

You got it!  What happens with ~ is somewhat more complicated...


Re: xor of unicode strings

2004-04-21 Thread Yitzchak Scott-Thoennes
On Wed, Apr 21, 2004 at 07:37:42AM -0700, Yitzchak Scott-Thoennes <[EMAIL PROTECTED]> 
wrote:
> On Wed, 21 Apr 2004, Bernie Cosell wrote:
> 
> > I'm not sure if this is 'fun', but it might be at least curious: I don't
> > have a UTF-8 system handy to try, but I'm wondering: what happens with
> > the string-xor operator on UTF-8 strings.  It obviously cannot work byte-
> > by-byte, but it seems like it is going to be a bit tricky figuring out
> > what you get when you xor a 1 byte character with a 2-byte one [I guess
> > what it would have to do to be 'correct' would be to convert the UTF to
> > "real Unicode", XOR the 32-bit "characters" together, and then compress
> > that resulting "character" back to UTF-8...
> 
> You got it!  What happens with ~ is somewhat more complicated...

Actually, pedantically, the "32-bit" part is wrong; perl will use
whatever normal unsigned integer type it knows about, which may very
well be 64-bit.  While the UTF-8 format is technically only defined up
to 21 bits, perl just switches as needed to an extension of the format
to provide up to 72 bits per character, which avoids having to do
range checking all over (though only 32 or 64 bits will be actually
usable, depending on perl's configuration).


Re: unhead

2004-09-24 Thread Yitzchak Scott-Thoennes
On Fri, Sep 24, 2004 at 03:17:56PM +0100, Jose Alves de Castro wrote:

> print if ($N+1)..0;

Implicit comparison to $. only happens for constants, so that
should be ($. > $N) .. 0


Re: unhead

2004-09-26 Thread Yitzchak Scott-Thoennes
On Sat, Sep 25, 2004 at 07:09:31PM -0700, "Randal L. Schwartz" <[EMAIL PROTECTED]> 
wrote:
> Well, it also presumes that "!" returns literally 0 and 1.  I've
> never seen a promise of that in any docs.

$ perl -we'use overload "!"=>sub{"whoa"}; print !bless{}'
whoa

> I think Perl6 should return "42" for true, just to keep people
> from making that presumption.

overload notwithstanding, it's a useful presumption.

In any case, it doesn't return literally 0; it returns PL_sv_no, which
has a numeric value of 0 and a string value of "".


Re: P2P in 15 lines

2004-12-16 Thread Yitzchak Scott-Thoennes
On Thu, Dec 16, 2004 at 08:08:11AM -0800, Brad Greenlee wrote:
> That or someone with sufficient power could make Digest::MD5 or ::SHA1 
> part of the standard perl distro :-).

Digest and Digest::MD5 are in 5.8.0.


Re: crashing on the full moon

2005-01-12 Thread Yitzchak Scott-Thoennes
On Fri, Jan 07, 2005 at 06:59:35PM -0800, Josh Goldberg wrote:
> A (java programming) coworker presented this challenge while discussing 
> a hypothetical situation:
> 
> >* Chris troubleshoots and sees that David (in a moment of sheer 
> >insanity) coded the site to crash at 5:42pm on every full moon (do I 
> >hear a Perl Monger side say there is a Perl library for just such a 
> >thing -- and it's only 2 lines?).

Acme::Apache::Werewolf is probably something like what he wants.


Re: "Secret" operators

2005-02-01 Thread Yitzchak Scott-Thoennes
On Tue, Feb 01, 2005 at 01:20:21PM -0500, Bernie Cosell wrote:
> On 1 Feb 2005 at 12:36, Ronald J Kimball wrote:
> 
> > ... A list assignment in scalar context
> > returns the number of elements on the right-hand side of the assignment.
> 
> Which is an odd inconsistency, because in list context a list assignment 
> returns the left-hand-side-list, so you might guess that in scalar 
> context it'd return the number of elements in the lhs list...

But the lhs usually either has a fixed number of elements or includes
arrays/hashes so the number of elements is arbitrarily large.  Using
the rhs allows common idioms like:

  while (my ($k, $v) = each %hash) {
  }

Here list-context each returns 2 elements (a key/value pair) until the
hash is exhausted, whereupon it returns 0 elements, terminating the loop.


Re: "Secret" operators

2005-02-03 Thread Yitzchak Scott-Thoennes
On Tue, Feb 01, 2005 at 09:02:56PM -, McGlinchy, Alistair wrote:
> Unfortunately -+- is bugged [*], but I'll leave these as gotcha's for
> your production code. :-)
> 
> [*] You might want to consider: print-+- '-2B'  x 5;  # Bug?

No.  perlop say: if the string starts with a plus or minus, a string
starting with the opposite sign is returned.


Re: "Secret" operators

2005-02-03 Thread Yitzchak Scott-Thoennes
On Wed, Feb 02, 2005 at 04:20:05PM +0200, Vladi Belperchinov-Shabanski wrote:
> On Wed, 2 Feb 2005 12:33:35 +1100 (EST)
> Andrew Savige <[EMAIL PROTECTED]> wrote:
> 
> > Jos_ Castro wrote:
> > > Apart from the "secret eskimo greeting" and the "goatse operator",
> > > can anyone tell me about other "secret" operators?
> > 
> > Let's not forget the Ton Hospel "high-precedence decrement"
> > operator ~- invented during a golf tournament (anyone remember
> > which one?).
> > 
> > IIRC, Ton's ~- invention allows you to eliminate the parens in:
> > 
> > $y = ($x-1)*4;
> > 
> > by using instead:
> > 
> > $y = ~-$x*4;
> > 
> > saving a whopping two strokes. This trick should work on any
> > twos complement machine -- and I'm not aware of any perl running
> > on any non twos complement machine.
> 
> will not work if $x < 0

Except under "use integer".  A little known fact is that perl's bitops
cast operands to unsigned integers without "use integer" and to signed
integers with "use integer".


Re: Unknown level of hash

2005-03-28 Thread Yitzchak Scott-Thoennes
On Mon, Mar 28, 2005 at 03:06:41PM -0800, Zhuang Li wrote:
> Hi, given an array: @a = ('E1', 'E2', ..., 'En'); 
> Is there an easy way, hopefully one liner, to do the following without a
> loop? If not, will Perl support this in Perl 6?
> 
> $hash->{E1}->{E2}->...->{En} = 1;

To read from such a series of hash keys is trivial:

$entry = $hash;
$entry = $entry->{$_} for @a;
print $entry;

To set it, you need to just do the same thing except that at each step
instead of keeping the hash element, you keep a reference to it:

$entryref = \$hash;
$entryref = \$$entryref->{$_} for @a;
$$entryref = 1;

Note that this will create hashrefs at any undefined levels, even the
top one.


Re: Unknown level of hash

2005-03-28 Thread Yitzchak Scott-Thoennes
On Tue, Mar 29, 2005 at 05:50:18AM +, Ton Hospel wrote:
> I always found the code to do this WITH a loop quite funny in fact:
> 
> my $work = \$hash;
> $work = \$$work->{$_} for @a;
> $$work = 1;

Ha ha ha :)


Re: Unknown level of hash

2005-03-29 Thread Yitzchak Scott-Thoennes
On Tue, Mar 29, 2005 at 11:45:01AM +0200, Alexandre Jousset wrote:
> Yitzchak Scott-Thoennes wrote:
> >To set it, you need to just do the same thing except that at each step
> >instead of keeping the hash element, you keep a reference to it:
> >
> >$entryref = \$hash;
> >$entryref = \$$entryref->{$_} for @a;
> >$$entryref = 1;
> >
> >Note that this will create hashrefs at any undefined levels, even the
> >top one.
> 
>   I'm sorry but that doesn't work as is on my system: "Not a HASH 
> reference at x.pl line 9.".

Works for me.  Can you show the actual code you are trying?


Re: Matching at least $x words out of @words

2005-05-06 Thread Yitzchak Scott-Thoennes
On Thu, May 05, 2005 at 09:41:46PM -0400, Rick Delaney wrote:
> On Fri, May 06, 2005 at 02:05:02AM +0200, A. Pagaltzis wrote:
> > * Jos? Castro <[EMAIL PROTECTED]> [2005-05-05 16:30]:
> > > So suppose you want a regular expression to match at least one
> > > of three words:
> > > 
> > > /word1|word2|word3/
> > > 
> > > What solution would you use if you wanted at least _two_ of
> > > those three words?
> > 
> > $alt = join '|', qw( word1 word2 word3 );
> > / ($alt) .* ($alt) (?(?{ $1 eq $2 })(?!)) /x
> 
>   / ($alt) .* (?!\1) ($alt) /x;

Fails with words: (foo, foobar, foobaz) and string "foofoobar".


Re: Table of Perl 5 Operators

2005-05-18 Thread Yitzchak Scott-Thoennes
On Wed, May 18, 2005 at 10:39:49AM +0100, Jos? Castro wrote:
> * Michael G Schwern ([EMAIL PROTECTED]) wrote:
> > So... did I miss anything?
> 
> Should //= be in there? Because my perl 5.8.6 doesn't seem to have it...

It's in 5.9.x, or you can add it to 5.8.6 with this patch:
http://perl.com/CPAN/authors/id/H/HM/HMBRAND/dor-5.8.6.diff


algorithmic challenge

2005-11-17 Thread Yitzchak Scott-Thoennes
This may be of interest to some:

Puzzle: The Ham Cheese Sandwich cut.
http://perlmonks.org/?node_id=509409


Re: swapping two numbers

2006-06-25 Thread Yitzchak Scott-Thoennes
On Sun, Jun 25, 2006 at 12:31:19AM -0700, Larry Rosler wrote:
> > From: Philippe "BooK" Bruhat
> > Sent: Saturday, June 24, 2006 04:10
> > To: fwp@perl.org
> > Subject: Re: swapping two numbers
> >
> >
> > Le vendredi 23 juin 2006 ? 17:40, Samy Kamkar ?crivait:
> > > Although x could overflow in this case, where it wouldn't with an xor,
> > > right?
> >
> > I've quickly tried to overflow it, but I didn't manage to break it.
> > It looks like even if you overflow x with the first addition, you
> > cross the border in the other direction when doing the substraction.
> >
> > --
> >  Philippe "BooK" Bruhat
> 
> The issue has nothing to do with overflow; everything to do with loss of
> precision.  Subtraction of two nearly equal numbers, or addition of two
> numbers of opposite sign and nearly equal magnitude) followed by a second
> similar computation can produce results with few or no significant bits.
> 
> The only correct way to perform these in-place swap operations is to treat
> the operands as bit patterns and use the xor operation.

I disagree.

If we are talking about non-integers (or integers whose magnitude
exceeds the available precision), xor isn't even a possibility in pure
perl; +/- is the only possiblity, with the loss-of-precision you
mention restricting which values it will perfectly work for.

But if we are talking about integers, so long as the intermediate
values stay in a fully representable range (usually 53 bits) there's
no problem with the +/- approach; the xor approach, on the other hand,
will only work correctly with operands representable as unsigned ints
of the size chosen by perl's configure (under no integer) or signed
ints (under use integer).

Either way, xor is the loser.


date validation via regex

2011-11-15 Thread Yitzchak Scott-Thoennes
This is something people often ask for.  The stock answer is that
regexes aren't the correct solution, but really it's not so hard.

This validates Gregorian MM/DD/CCYY dates, for example:

qr#^
(?: 0[1-9] | 1[012] )
/
(?:
0[1-9] | 1[0-9] | 2[0-8]
| (?

Re: date validation via regex

2011-11-15 Thread Yitzchak Scott-Thoennes
On Tue, Nov 15, 2011 at 11:10 AM, Brian Fraser  wrote:
> No. Just, no.

On this list, I think that counts as high praise.  Thanks!

> Read this:
> http://stackoverflow.com/questions/4077896/perl-or-python-convert-date-from-dd-mm--to--mm-dd/4078817#4078817

Err, which part?  tchrist is an expert on dealing with unicode in
various languages/regex engines and in real-world "text" data, but I
think he's overreaching there; I don't expect my date strings to
include non-ASCII digits.  I can see some software butchering - into a
non-ASCII dash character, but I'd tend to treat fixing that as a
separate problem.  (Though that was actually a motivation in having my
regex looking for /, not -.)

> Then forget about using regexen and find a module to do it for you.
> Regexp::Common::time is pretty nice, albeit slow if you are doing millions
> of validations.
> (But in the spirit of this list, sure, that's cool. Would be cooler if you
> could abstract it using (?(DEFINE)) :)

Meh.  I think that would only obfuscate it.


Re: Rate my JAPH

2011-12-07 Thread Yitzchak Scott-Thoennes
Sorry, Randal (initially sent this only to him).

On Wed, Dec 7, 2011 at 10:48 AM, Randal L. Schwartz
 wrote:
>> "Andrew" == Andrew Savige  writes:
>
> Andrew>  print "Just another Perl hacker,"
>
> That's missing the trailing semicolon.  I was pretty consistent on
> putting that there.

Ooh, it's been a long time since I've seen a good statement-separator vs.
statement-terminator religious argument.  Was that an opening salvo?


Re: The sperm secret operator: is it new?

2012-03-14 Thread Yitzchak Scott-Thoennes
On Wed, Mar 14, 2012 at 7:48 AM, John Douglas Porter
 wrote:
> So is that the Perl 6 smart match operator? or something else?

The latter.

> In any case... How does it work here?  It looks like it's functionally
> equivalent to scalar()... but why?

Perl's ~ is operand sensitive; if its operand has a numeric value
(either because it was assigned a number, the result of a numeric
operation,  or had been used in numeric context), it is a numeric
bitwise or (implicitly converting to UV, or under the scope of use
integer, IV, first); otherwise it is a string bitwise or.

For most inputs, in either case it can be repeated to reproduce the
original value and acts just like scalar().

Examples of exceptions:

# floating point

$x = 1.23; print ~~$x; # 1

# string used in numeric context

$x = "1.23"; print ~~$x if $x != 0; # 1

# integer out of range

use Config '%Config';

$x=2**(8*$Config{uvsize}); print ~~$x; # max uv

$x = -1; print ~~$x; # max uv

$x = 2**(8*$Config{uvsize}-1); use integer; print ~~$x; # min iv

$x = -2**(8*$Config{uvsize}-1)-1; use integer; print ~~$x; # min iv


Re: The sperm secret operator: is it new?

2012-03-14 Thread Yitzchak Scott-Thoennes
On Wed, Mar 14, 2012 at 3:50 PM, Philippe Bruhat (BooK)
 wrote:
> Frankly, I think this could be considered a bug. Both the left-facing
> and right-facing versions of the inchworm on a stick should work on
> all integers in Perl. Complement two arithmetics demand it! Now, the
> question is, how long has this been broken in Perl? Forever?

I don't consider it a bug.  ~ has to either assume signed or unsigned.

You get a choice by whether you do it under the scope of use integer
(implicit: comma signed) or not.