Re: seeking golfing advice

2012-05-18 Thread Aristotle Pagaltzis
* Steve Fink sph...@gmail.com [2012-05-18 10:25]:
 On Thu, May 17, 2012 at 3:14 AM, Aristotle Pagaltzis pagalt...@gmx.de wrote:
  * Mike Erickson m...@quidquam.com [2012-05-16 15:45]:
   If you don't care about order, but just want those elements, you
   can also do:
  
   keys%{{@a}}
 
  There is more than order that gets lost. If you use `keys` you also
  get everything back stringified – undefs are lost and references
  break. If you use `values` these problems go away… except that to
  get the odd-index elements from it you have to `reverse` the array,
  at which point a not-especially-golfed grep is shorter.

 So you'd want

  values%{{1,@a}}

 then

D’oh!


Re: seeking golfing advice

2012-05-17 Thread Aristotle Pagaltzis
* Mike Erickson m...@quidquam.com [2012-05-16 15:45]:
 If you don't care about order, but just want those elements, you can
 also do:

 keys%{{@a}}

There is more than order that gets lost. If you use `keys` you also get
everything back stringified – undefs are lost and references break. If
you use `values` these problems go away… except that to get the odd-
index elements from it you have to `reverse` the array, at which point
a not-especially-golfed grep is shorter.

-- 
*AUTOLOAD=*_;sub _{s/$/$/;s/(.*):://;wantarray//substr$_,-1,1,,$/;print;$1}
Just-another-Perl-hack;
#Aristotle Pagaltzis // http://plasmasturm.org/


Re: seeking golfing advice

2012-05-17 Thread Aristotle Pagaltzis
* Pau Amma paua...@gundo.com [2012-05-16 14:55]:
 If, as it sounds, you want to balance golfiness and strictness, you
 could also say:

 @array[grep $_%2, keys @array]

 (or @array[grep $_%2^1, keys @array] if you set $[ to 1 - but you
 didn't do that, right? :-) )

Btw, `keys@foo` and `0..$#foo` are equally long… but the latter works
with old perls (advantage production) *and* looks more line-noisy
(advantage golf).

And if you have an array to work with in the first place, you can also

@array[map 1+$_*2, 0..$#array/2]

which is 3 characters longer than the grep version in exchange for doing
half as much work. (For even elements, the map and grep solutions would
yield exactly equally long code, with half-as-much-work still applying.)

-- 
*AUTOLOAD=*_;sub _{s/$/$/;s/(.*):://;wantarray//substr$_,-1,1,,$/;print;$1}
Just-another-Perl-hack;
#Aristotle Pagaltzis // http://plasmasturm.org/


Re: decimal - Binary

2011-11-18 Thread Aristotle Pagaltzis
* Ronald J Kimball rjk-perl-...@tamias.net [2011-11-16 21:50]:
 It is greedy, but the important thing to remember is that the regular
 expression engine will find the longest *leftmost* match.

To put that a third way: the engine will match at the first possible
location, and will make the match as long as possible at that location.


Re: regex of the month (decade?)

2008-01-12 Thread Aristotle Pagaltzis
* Chris Dolan [EMAIL PROTECTED] [2008-01-12 23:55]:
 I figured that anyone who lives in a country whose dominant
 language was not fully expressible in ASCII would love Unicode.

For bonus points, try writing, say, German (fully expressible
with an ISO-8859 charset) and Greek (fully expressible[^1] with
an ISO-8859 charset) in the same document.

[1]: Well, Modern Greek anyway.

Regards,
-- 
Aristotle Pagaltzis // http://plasmasturm.org/


Re: bad code to good golf

2007-12-10 Thread A. Pagaltzis
* shmem [EMAIL PROTECTED] [2007-12-10 12:55]:
 Well, if we were to return an array reference instead of a hash
 ref,
 
 sub [EMAIL PROTECTED],shift}
 
 works. Why does the shift get executed before an array
 reference is constructed - but not if a hashref is constructed
 - from an array?

It probably doesn’t. Either way, evaluation order is a red
herring: your construction will work regardless of which
subexpression is evaluated first!

You managed to confuse yourself. Congratulations. :-)  (Or you
are underhandedly trying to confuse us. In that case, sorry bub,
better luck next time. :-) )

What happens is that `\` takes a *reference* to the array. And
of course when you do that, any modifications of the referent,
including *subsequent* modifications, will be seen by anyone who
holds a reference to it.

In contrast, the hash constructors make a *copy* of the array,
and that copy will not be affected but subsequent modifications
to the source array.

Anyone who has trouble following should consider the difference
between the following two:

sub new { bless [EMAIL PROTECTED], shift }
# vs
sub new { bless [EMAIL PROTECTED], shift }

Consider how many arrays are involved in either case, and which
one is affected by the `shift`.

-- 
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1}
Just-another-Perl-hack;
#Aristotle Pagaltzis // http://plasmasturm.org/


Re: bad code to good golf

2007-12-09 Thread A. Pagaltzis
* Uri Guttman [EMAIL PROTECTED] [2007-12-09 19:25]:
 * Michael G Schwern [EMAIL PROTECTED] writes:
 sub new {
   my $class = shift;
   return bless( [EMAIL PROTECTED], $class );
 }
 
 my clean version is:
 
 sub new {
   my ( $class, %self ) = @_ ;
   return bless \%self, $class ;
 }
 
 i don't like using shift for args if i can help it.

Personally I *always* use `shift` for the invocant, but
assignment from [EMAIL PROTECTED] for all other parameters in all but a few
rare circumstances. So methods in my code always read something
like this:

sub frobnitz {
my $self = shift;
my ( $foo, $bar, $baz ) = @_;
# ...
}

It’s a nod to the fact that the invocant is not really in the
same class (no pun intended) as the other parameters. Since
`$self` is thus removed from [EMAIL PROTECTED], and is the *only* thing
removed from it, that also makes it natural to write delegative
code:

# ...
$self-get_veeblefitzer()-frobnitz( @_ );
# ...

-- 
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1}
Just-another-Perl-hack;
#Aristotle Pagaltzis // http://plasmasturm.org/


Re: fun with hashes!

2007-11-24 Thread A. Pagaltzis
* David Landgren [EMAIL PROTECTED] [2007-11-24 10:45]:
 Uri Guttman writes:
 AP == A Pagaltzis [EMAIL PROTECTED] writes:
   AP * Jerrad Pierce [EMAIL PROTECTED] [2007-11-23 22:50]:
exists( $dispatch{$sub} ) ? $dispatch{$sub}-() :
warn Key $sub does not exist in the dispatch table;
   AP ( $dispatch{$sub} || sub { warn no such action '$sub' } )-();
 some variations on that:
  my $sub = $dispatch{$key} or die trying to call missing code ;
  $sub-() ;
 or:

 [...]

 or:
  my $sub = $dispatch{ $key } || $dispatch{ 'default' } ;

 Why stop there? Assuming $key never evaluates to 0:

   my $sub = $dispatch{ $key || 'default' };

Your dispatch table has keys for all nonzero strings?

That’s one big hash.

Regards,
-- 
Aristotle Pagaltzis // http://plasmasturm.org/


Re: fun with hashes!

2007-11-23 Thread A. Pagaltzis
* Mr. Shawn H. Corey [EMAIL PROTECTED] [2007-11-24 00:50]:
 my $sub = ( exists $dispatch{ $key }  ref( $dispatch{ $key } ) eq 'CODE' )
  ? $dispatch{ $key }
  : $dispatch{ 'default' };

 Just because you're not paranoid doesn't mean computers don't
 hate you :)

So why did you skip the check for whether the default value is
a CODE ref?

Regards,
-- 
Aristotle Pagaltzis // http://plasmasturm.org/


Re: fun with hashes!

2007-11-23 Thread A. Pagaltzis
* Jerrad Pierce [EMAIL PROTECTED] [2007-11-23 22:50]:
 exists( $dispatch{$sub} ) ? $dispatch{$sub}-() :
  warn Key $sub does not exist in the dispatch table;

( $dispatch{$sub} || sub { warn no such action '$sub' } )-();

-- 
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1}
Just-another-Perl-hack;
#Aristotle Pagaltzis // http://plasmasturm.org/


Re: Minimal DNS answer using Net::DNS

2006-11-26 Thread A. Pagaltzis
* Kelly Jones [EMAIL PROTECTED] [2006-11-26 08:00]:
 I've used xinetd to set up a test nameserver on port 1024.
 Here's the Net::DNS Perl I'm using to say (falsely) that
 news.yahoo.com resolves to 10.1.2.3 with a TTL of 1 day:

Hmm. Your question is not very Fun, so this is the wrong list to
ask. You probably want to take this to Perlmonks.

Regards,
-- 
Aristotle Pagaltzis // http://plasmasturm.org/


Re: local vs. my (was Re: code line of the day)

2006-09-10 Thread A. Pagaltzis
Hi Chris,

* Chris Dolan [EMAIL PROTECTED] [2006-09-09 21:00]:
 I didn't mean that to be insulting -- I was just teasing. […]
 That was for my curiosity and to convince me, […] I apologize
 for my less-than-clear motives.

no problem, not your fault. I’m a bit impatient sometimes, which
can lead to unwarranted grumpiness.

Regards,
-- 
Aristotle Pagaltzis // http://plasmasturm.org/


Re: code line of the day

2006-09-08 Thread A. Pagaltzis
* Chris Dolan [EMAIL PROTECTED] [2006-09-08 17:10]:
 Why did you use local?  Shouldn't the following work?
 
 sub flatten_copy {
 my $s = shift;
 ref $s eq 'SCALAR' ? $$s : $s;
 }

Works the same. I often use `local $_` in tiny functions that
mangle just a single value. Matter of taste/style.

Regards,
-- 
Aristotle Pagaltzis // http://plasmasturm.org/


Re: code line of the day

2006-09-07 Thread A. Pagaltzis
* Uri Guttman [EMAIL PROTECTED] [2006-09-07 09:30]:
 this line of my code grew to its present form which i find amusing. 
 
   @{$self-{templates}}{ keys %{$tmpls} } =
   map ref $_ eq 'SCALAR' ? \${$_} : \$_, values %{$tmpls} ;

my ( $k, $v );
$self-templates-{ $k } = ref $v eq 'SCALAR' ? \${$v} : \$v
while ( $k, $v ) = each %$tmpls;

Hmm. Don’t think I like that better.

[ delete 3 different attempts to make it better ]

Ugh. I think the core problem is that Perl actually does very
little to help you operate on hashes as a whole.

Regards,
-- 
Aristotle Pagaltzis // http://plasmasturm.org/


Re: Super regexp to format numbers

2006-08-28 Thread A. Pagaltzis
* Alexandre Jousset [EMAIL PROTECTED] [2006-08-28 18:15]:
 For the moment I have a (too) complicated sub spacify and I would 
 like to simplify it to a regexp.

It doesn’t have to be complicated, even without a regexp.

scalar reverse join ' ', unpack '(A3)*', reverse $num;

Regards,
-- 
#Aristotle
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1};
Just-another-Perl-hacker;


Re: Including externally-defined constants

2006-07-20 Thread A. Pagaltzis
* Philippe BooK Bruhat [EMAIL PROTECTED] [2006-07-20 08:40]:
 Le jeudi 20 juillet 2006 à 02:41, A. Pagaltzis écrivait:
 * Philippe BooK Bruhat [EMAIL PROTECTED] [2006-07-19 22:10]:
  '=cut';
 
 =pod
 
 [...snip...]
 
 =cut
 
 Damn, what a cool hack!
 
 That's exactly what I thought when I first saw it. :-)

I just abused it further, check it out:
http://www.perlmonks.org/index.pl?node_id=562735

Regards,
-- 
#Aristotle
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1};
Just-another-Perl-hacker;


Re: Naming the @{[]} operator

2006-07-13 Thread A. Pagaltzis
* Bart Lateur [EMAIL PROTECTED] [2006-07-13 11:30]:
 On Thu, 13 Jul 2006 04:29:38 -0400, Chasecreek Systemhouse wrote:
 What the advantage the above over this:
 
 perl -le 'print time'
 
 Oh come on, you asked how to use @{[]}.

It’s a legitimate question.

Another use case:

for( qw( 1 2 3 ) ) {
$_ = $_ * $_; # contrived
print square: $_\n;
}
__END__
Modification of a read-only value attempted at foo line 2.

as opposed to

for( @{[ qw( 1 2 3 ) ]} ) {
$_ = $_ * $_; # contrived
print square: $_\n;
}
__END__
square: 1
square: 4
square: 9

In other words it’s also useful when you need to break aliasing
to make sure you’re operating on a modifiable copied scalar.

Regards,
-- 
Aristotle Pagaltzis // http://plasmasturm.org/


Re: Naming the @{[]} operator

2006-07-11 Thread A. Pagaltzis
* Smylers [EMAIL PROTECTED] [2006-07-11 23:05]:
 babycart is 3 syllables; shopping trolley
 
Plus I could see myself adopting the latter (reluctantly) if it
became part of the vernacular, but I’d feel too silly using the
former to pick it up.

I still like “fat brackets” better though, in vague analogy to
the “fat comma.”

Regards,
-- 
#Aristotle
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1};
Just-another-Perl-hacker;


Re: Converting dell tags to svc codes - itty-bitty golf, anyone?

2006-02-22 Thread A. Pagaltzis
* [EMAIL PROTECTED] [EMAIL PROTECTED] [2006-02-22 20:15]:
map {$s+=(/\d/?$_:(ord()-55))*(36**$i++)} reverse(split(//,uc shift)); 
 @v{ 0..9, A..Z } = 0..35; $s = $s * 36 + $v{ uc $_ } for /./g;

Even readably spaced, the less clever solution is shorter.

$s =~ s/(...)/$1-/g; print $s\n; 
 print join '-', $s =~ /(..?.?)/g;
 print join '-', unpack '(A3)*', $s;

Again, less clever and readably spaced is still shorter, though
the win is a lot more marginal.

With List::Util you can even write this as a single expression
(modulo initializing the lookup table, of course).

print
join '-',
unpack '(A3)*',
reduce { $a * 36 + $v{ uc $b } }
0, /./g;

I’d argue that this is rather readable too.

All solutions in direct comparison:

#   12345678
910
#2345689 12345689 12345689 12345689 12345689 12345689 12345689 12345689 
12345689 12345689 12345689
map{$s+=(/\d/?$_:(ord()-55))*(36**$i++)}reverse(split(//,uc 
shift));$s=~s/(...)/$1-/g;print$s\n;
@v{0..9,A..Z}=0..35;$s=$s*36+$v{uc$_}for/./g;print join'-',$s=~/(..?.?)/g;
@v{0..9,A..Z}=0..35;$s=$s*36+$v{uc$_}for/./g;print join'-',unpack'(A3)*',$s:
@v{0..9,A..Z}=0..35;print 
join'-',(reduce{$a*36+$v{uc$b}}0,/./g)=~/(..?.?)/g;
@v{0..9,A..Z}=0..35;print 
join'-',unpack'(A3)*',reduce{$a*36+$v{uc$b}}0,/./g;

You may or may not consider it cheating that I left out the
`use List::Util 'reduce';` stanza in my `reduce` examples.
But you appear to be wanting to use this is production code, so
I don’t think pure golfage is really what you’re after.

Regards,
-- 
#Aristotle
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1};
Just-another-Perl-hacker;


Re: [ANNOUNCE] first release of PerlWar (and request for beta testers)

2005-10-17 Thread A. Pagaltzis
* Yanick Champoux [EMAIL PROTECTED] [2005-10-18 03:05]:
 Well, I'll be darned. Some people actually volunteered. :-)

You might garner some more interest by posting this to
rec.games.corewar – they’re always interested in hearing about
variations on the game.

Regards,
-- 
#Aristotle
*AUTOLOAD=*_=sub{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1};
Just-another-Perl-hacker;


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

2005-05-09 Thread A. Pagaltzis
* A. Pagaltzis [EMAIL PROTECTED] [2005-05-09 12:10]:
 The problem with this and all the grep solutions is that you
^^
 dont know whether you matched the same alternate multiple
 times,

Err, that bit was non-sense, of course. I need some coffee.

Regards,
-- 
#Aristotle
*AUTOLOAD=*_=sub{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1};
Just-another-Perl-hacker;


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

2005-05-05 Thread A. Pagaltzis
* 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

Note:
It can probably be reduced further to remove the need for $alt
duplication in the regex. The only way I can see would entail
using (?{}) and local to save matches, though.

Warning:
Lots of backtracking. Use a grep solution as shown by others in
pratice.

Regards,
-- 
#Aristotle
*AUTOLOAD=*_=sub{s/(.*)::(.*)/print$2,(,$\/, )[defined wantarray]/e;$1};
Just-another-Perl-hacker;


Re: Load-Bearing Warnings

2004-08-03 Thread A. Pagaltzis
* Smylers [EMAIL PROTECTED] [2004-08-04 00:34]:
   [*0]  It was cluttering up the error log with benign 'uninitialized'
   messages, which were obscuring the output (from some other script)
   that I wanted to see.

Maybe you can try just disabling those?

no warnings 'uninitialized';

Regards,
-- 
Aristotle
If you can't laugh at yourself, you don't take life seriously enough.


Re: error handling in perl modules

2004-06-25 Thread A. Pagaltzis
* Babichev Dmitry [EMAIL PROTECTED] [2004-06-25 09:17]:
 Could anybody provide the best practices of implementation the
 error handling in perl modules?

This is the fun with Perl list. Your inquiry is No Fun.

You want to go to www.perlmonks.org or some such.

Regards,
-- 
Aristotle
If you can't laugh at yourself, you don't take life seriously enough.


Re: Golf challenge: Tangled Tale

2004-06-24 Thread A. Pagaltzis
* Tobias Gödderz [EMAIL PROTECTED] [2004-06-24 23:42]:
 Okay, I'm down to 148 now, and I think, I'm on my limit. I'll
 publish mine as soon as no one wants to compete anymore.

I am working on a solution, but I don't think I'll manage to
finish tonight, and tomorrow I'll be gone from home until after
the weekend, so it'll likely take me a couple of days before I
can even say how many chars I estimate it's gonna be.

Just so you don't draw conclusions too quickly. :-)

Regards,
-- 
Aristotle
If you can't laugh at yourself, you don't take life seriously enough.


Re: Golf challenge: Tangled Tale

2004-06-23 Thread A. Pagaltzis
* Brad Greenlee [EMAIL PROTECTED] [2004-06-21 00:37]:
 Golf anyone? My opening shot is 288.

* Tobias Gödderz [EMAIL PROTECTED] [2004-06-23 19:16]:
 We (a friend of mine and me) made it with 246 chars.

Uh, you're supposed to publish your solutions when golfing.

Regards,
-- 
Aristotle
If you can't laugh at yourself, you don't take life seriously enough.


Re: Regular expression for years after a given one

2004-06-01 Thread A. Pagaltzis
* Jose Alves de Castro [EMAIL PROTECTED] [2004-06-01 11:59]:
 BTW: This was made so it would work with $year consisting of
 four digits... any care to make it generic? :-)

sub rx_gt {
local $_ = shift;
return if /\D/;
my @alt = '';
for(split //) {
$_ .= '\d' for @alt[ 1 .. $#alt ];

if($_ = 7) {
unshift @alt, $alt[0];
$alt[0] .= $_;
$alt[1] .= [EMAIL PROTECTED] $_+1 ]}-9];
}
elsif($_ == 8) {
unshift @alt, $alt[0];
$alt[0] .= 8;
$alt[1] .= 9;
}
else { # == 9
$alt[0] .= 9;
}
}
shift @alt;
my $rx = join '|', @alt;
return (?:$rx);
}

$_ = 14987345;
print map $_\n, $_:, rx_gt $_;

-- 
Gruss,
Aristoteles
 
Wer nicht über sich selbst lachen kann, nimmt das Leben nicht ernst genug.


Re: Regular expression for years after a given one

2004-06-01 Thread A. Pagaltzis
* Tobias Wolter [EMAIL PROTECTED] [2004-06-01 17:33]:
 On 2004-06-01T10:52:55+0100 (Tuesday), Jose Alves de Castro wrote:
  How can I say that I want every single year after the one I
  have? It's impossible...
 
 The  operator works quite well for a four-digit year.

Yeah, but that requires backing out of the pattern match into
Perl context, as saving the required information isn't always
easy either.

Of course you could use such a numerical comparison in a Perl
code subexpression as several people here have done, but that is
also a switch of context.

There may also be cases where the interface to some other part of
code will only allow you to pass in a pattern, not a coderef or
something else, and where re 'eval' is not enabled.

There are definitely circumstances where using a regex to do
numerical comparison is the best option.

And anyway, did you notice what this list is called?

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: Reading X lines at a time

2004-05-09 Thread A. Pagaltzis
* Rick Delaney [EMAIL PROTECTED] [2004-05-03 15:23]:
 while (my @a = map { eof() ? () : scalar  } 1 .. $n) {
 print @a;
 print SEPARATOR\n;
 }

 while (my @a = grep defined, map scalar , 1 .. $n) {
 print @a;
 print SEPARATOR\n;
 }

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: Break the 65 chars :-)

2004-04-26 Thread A. Pagaltzis
* Jose Alves De Castro [EMAIL PROTECTED] [2004-04-26 18:36]:
 #!/usr/bin/perl -l0n
 /:/;$_{$'.$}.= $`,}{map{s/,$/
 /;print}%_

Trivial improvement, for a gain of 5 chars:

#!/usr/bin/perl -l0p
/:/;$_{$'.$}.= $`,}for(%_){s/,$/
/;

I've tried other clever things, but they all come out longer.

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: fractional cents

2004-04-25 Thread A. Pagaltzis
* Keith C. Ivey [EMAIL PROTECTED] [2004-04-22 14:48]:
 Math won't work, because floats aren't exact.

Actually, that is a point I meant to make somewhere in this
thread.

When you're dealing with money, it's better to use cents (or
tenths or hundredths of cents) as a unit, rather than dollars.
You can then use integer math. This gets you around all the
problems with a base-2 representation of base-10 fractions,
something you don't want to have to deal with when money is on
the line..

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: fractional cents

2004-04-21 Thread A. Pagaltzis
* John Douglas Porter [EMAIL PROTECTED] [2004-04-20 08:39]:
 It seems to me that the precision desired should depend on
 context, and nothing else.  And that being the case...
 
   printf $fractional_cents ? '%7.3f' : '%7.sf', $amt;
 
 irrespective of the value of $amt.  Why is this not right?

What you have written is neutral with regards to the issue I was
referring to.

If you do this by looking at $amt, then your method must be
mathematical, because chopping characters in the string
representation of the unrounded $amt might occasionally lead to
results different from what the mathematical method would have
produced with rounding involved.

If you already do have a string representation consistent with a
rounded $amt, f.ex using sprintf, then it's safe to mangle this
as a string.

So the key here would be what expression decides the value of
your $fractional_cents boolean. And I as I posted a bit before,
it *can* (of course) be done using just math.

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: fractional cents

2004-04-21 Thread A. Pagaltzis
* Bernie Cosell [EMAIL PROTECTED] [2004-04-22 00:02]:
 On 21 Apr 2004 at 22:55, A. Pagaltzis wrote:
  If you do this by looking at $amt, then your method must be
  mathematical, because chopping characters in the string
  representation of the unrounded $amt might occasionally lead to
  results different from what the mathematical method would have
  produced with rounding involved.
 
 Correct, but doesn't %.Xf round?  And so running it through
 the (s)printf before you mess with it gets you the desired
 rounding, doesn't it?

Yes, that's what I said further down in my mail.

The point is that using something like $amt =~ /\.\d\d\d/ will
probably lead to inconsistencies because $amt is unrounded, while
printf then produces a rounded form that depends on at least one
more digit, probably also on whether the non-fractional part is
odd or even, and a number of other factors.

So if your conditional refers to $amt, it should use math, like
($amt * 1000) % 10.

You *can* use string mangling, however, if you mangle the
*result*.

 When you're pricing things, prices are in dollars and cents
 except for [...]

I know what he wanted and why, and wasn't even saying anything
about that.

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: fractional cents

2004-04-19 Thread A. Pagaltzis
* Bernie Cosell [EMAIL PROTECTED] [2004-04-19 17:37]:
 So: what I want is something to format money correctly, whther
 it is fractional or not.  there's the fairly awful:
 
  sprintf ($amt =~ /\.\d\d\d/? %7.3f: %7.2f), $amt

Right off the bat I thought of %g, but that doesn't really help:

$ perl -e'printf %7.4g\n, $_ for 1.2, 1.23, 1.234, 1.2345'
1.2
   1.23
  1.234
  1.234

When testing $amt itself, I'd insist on using mathematical
functions only for the sake of cleanliness -- you never know when
stringification would surprise you. Unfortunately, getting the
fractional part of a number in Perl is verbose using mathematical
functions.

So instead I'd say to do string mangling on the end result, which
is only a string representation of $amt anyway:

my $amt_str = sprintf %7.3f, $amt;
for($amt_str) { chop if /\.\d\d0\z/ } 

Test:

perl -le'for (@ARGV) { $_ = sprintf %7.3f, $_; \
chop if /\.\d\d0\z/; print; }' 1.2, 1.23, 1.234, 1.2345
  1.20
  1.23
  1.234
  1.234

It's not shorter or more obvious I'm afraid, just a little more
correct.

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: fractional cents

2004-04-19 Thread A. Pagaltzis
* Quantum Mechanic [EMAIL PROTECTED] [2004-04-19 23:09]:
 --- A. Pagaltzis [EMAIL PROTECTED] wrote:
  my $amt_str = sprintf %7.3f, $amt;
  for($amt_str) { chop if /\.\d\d0\z/ } 
 
 Why would you do for..chop when you could do s///?
 You're using an re either way?
 
 ;)
 
 =
 ~~
 Quantum Mechanics: The dreams stuff is made of

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/;

The last one is even semantically different, even though it does
the same thing.

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: lvalue hash slice

2003-10-03 Thread A. Pagaltzis
* Gaal Yahas [EMAIL PROTECTED] [2003-10-03 11:24]:
 Two points about this. First, the lvalue ?: is kinda, uh,
 Perlish to the extreme.

Yeah. It tends to be a powerful obfuscant too. I had to look
thrice at your code (then went oh, duh!). For more than two or
maybe three lvalues to switch between, I avoid it.

 And second, of course after I'd looked at it again it became
 clear it could be refactored to be even more succinct. If I'm
 willing to leave sortorder inside the frgrp structure[*], this
 can easily be remade:
 
  for (keys %$res) {
  $frgrp{$1}{$2}  = $res-{$_}
   if /^frgrp_(\d+)_(name|public|sortorder)$/;
  $friend{$1}{$2} = $res-{$_}
   if /^friend_(\d+)_(user|name|groupmask|type)$/;
  }

Might be overkill in this case, but honouring capture
similarities in code, differences in data, I might be inclined
to write this along the lines of

my %parse_type_for = (
frgrp  = [ \%frgrp,  'name|public|sortorder' ],
friend = [ \%friend, 'user|name|groupmask|type' ],
);

for (keys %$res) {
my ($name) = /^([^_]+)/;
my ($type, $options) = @{$parse_type_for{$key}}
or next;

/^$name_(\d+)_($options)$/g
and $type-{$1}{$2} = $res-{$key};
}

I'm not happy with the name choice for ``$type'', but couldn't
think of a better term.

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: lvalue hash slice

2003-09-30 Thread A. Pagaltzis
* Gaal Yahas [EMAIL PROTECTED] [2003-09-30 20:14]:
 Sadly, this doesn't work as an lvalue:
 @hash{ qw/aaa bbb ccc/ } = ($one, $two, $three);

I use that *all* the time. The problem is not with Perl here..

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: Semcarlbd letrtes sepur! (Scrambled letters super!)

2003-09-18 Thread A. Pagaltzis
* Etienne Grossmann [EMAIL PROTECTED] [2003-09-18 09:29]:
 I hared a sutdy has been dnoe on taht scjebut in an Eigslnh
 urtiivesny, but I coannt get hold of it. Any ionirmtfoan on
 that sceujbt is welomce.

http://www.bisso.com/ujg_archives/000224.html

 perl -pe 'sub r{join,map chop,sort 
 map{rand().$_}shift=~/(.)/g};s/\b(\w)(\w*)(\w)\b/$1.r($2).$3/eg'

perl -pe's/(?=[a-z])([a-z]+)(?=[a-z])/join,map chop, sort map 
rand().$_,$1=~m[.]g/ige'
perl -MList::Util=shuffle 
-pe's/(?=[a-z])([a-z]+)(?=[a-z])/join,shuffle$1=~m[.]g/ige'

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: Semcarlbd letrtes sepur! (Scrambled letters super!)

2003-09-18 Thread A. Pagaltzis
* Kripa Sundar [EMAIL PROTECTED] [2003-09-18 15:41]:
 The following does guarantee re-ordering.

How does it reorder loop? :-)

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: Phalanx top 100 CPAN modules golf

2003-08-25 Thread A. Pagaltzis
* Andrew Savige [EMAIL PROTECTED] [2003-08-24 04:27]:
 the Klement Transform? Or should that read Klementian or even
 Klementine Transform? :-)

Well, it's not called the Guttman-Roslerian Transform (or
Guttmanian-Roslerian?) either.

Schwartzian is really a red herring.

-- 
Regards,
Aristotle
 
If you can't laugh at yourself, you don't take life seriously enough.


Re: Fun - Each character at most once

2003-07-25 Thread A. Pagaltzis
* Adam Rice [EMAIL PROTECTED] [2003-07-22 16:02]:
 I wrote a program to generate these, but has an unfun tendency
 to take forever when the solution is non-trivial so I won't
 post it. If there was a better technique than brute force to
 find the answers that might be fun, but I just can't get my
 head around it.

I don't see the problem. You have 36 (or 120) pairs or encoded
characters to allocate, and up to that many input characters.
Looks like just one straightforward mapping.

-- 
Regards,
Aristotle


Re: Fun - Each character at most once

2003-07-17 Thread A. Pagaltzis
* [EMAIL PROTECTED] [EMAIL PROTECTED] [2003-07-17 21:15]:
  What is the most interesting program that is restricted to
  use each ASCII character at most once?
 
 The definition I chose was to check if a program (from @ARGV)
 contains duplicate chars and  printing a duplicate char iff it
 has one.

Even ++, --, ==,  etc are illegal. A substitution based
approach is about impossible - you need a dot in several places
of the pattern, and if you have backreference you'll likely need
a capture variable with the same number in the replacement
expression as well. And finally, you can't refer to any variable
more than once.

That final one is the kicker.

Basically, with all ASCII characters used at most once, you can't
really write anything that needs to actually operate on data in
any more but the most trivial ways.

-- 
Regards,
Aristotle


Re: Is this fun?

2003-07-15 Thread A. Pagaltzis
* Jon Bjornstad [EMAIL PROTECTED] [2003-07-15 00:00]:
 I don't often get to use the '.' operator or the 'x' operator
 and I thought this was pretty cool.

Pretty standard fare for some people, though I guess the exact
idea of fun is different for everyone. :)

 There are a few flaws with the above approach.

More than those you mention - because it doesn't parse HTML, just
looks for some string bits. It will blow up on

img alt=a r g h ...

f.ex.

 Comments?  Other approaches?

If this is supposed to handle arbitrary HTML, not a narrow set of
input you already know it handles correctly, use a (tolerant)
parser. HTML::TokeParser(?:::Simple)? does nicely for jobs like
this.

 Is the s/// operator the only way (of course not!) to get the
 number of occurences of a regexp in a string?

m//g in scalar context is better.


for my $tag (qw[ol ul b i u a]) {
my ($opening, $closing) = (0)x2;
$opening++ while $frag =~ m!$tag\b!gi;
$closing++ while $frag =~ m!/$tag\b!gi;
$frag .= /$tag x ($opening - $closing);
}

Or maybe more elaborately in a single loop:

for my $tag (qw[ol ul b i u a]) {
my ($opening, $closing) = (0)x2;
until($frag =~ /\G\z/gc) {
++$opening if $frag =~ m!\G$tag\b!gci;
++$closing if $frag =~ m!\G/$tag\b!gci;
$frag =~ m!\G.[^]*!gc;
}
$frag .= /$tag x ($opening - $closing);
pos($frag) = 0;
}

At this point we're already closing in on the realm of parsers..
m//gc is how you build lexers in Perl.

-- 
Regards,
Aristotle


Re: Is this fun?

2003-07-15 Thread A. Pagaltzis
* Keith C. Ivey [EMAIL PROTECTED] [2003-07-15 14:42]:
 which will be handled by the regex but may cause a parser to
 blow up (though some are more tolerant than others)

Did you read what I said? You need a tolerant parser indeed. Did
you take any look HTML::Parser at all?

 | That leaves input data munging, which I do a lot of, and a
 | lot of input data these days is XML. Now here's the dirty
 | secret; most of it is machine-generated XML,

Is yours?

 | I've even gone to the length of writing a prefilter to glue
 | together tags that got split across multiple lines, just so I
 | could do the regexp trick.

Do you?

Sure, you as long as you know your input follows narrower
specifications then arbitrary valid markup, you can use that
knowledge to your advantage.

The deficiencies with parsers are their interfaces; what we
really need is a generic matching engine that can be applied to
ordered collections not only of characters, but of arbitrary
objects for some, so that we could apply a pattern to, say, a
stream of XML parser events.

-- 
Regards,
Aristotle


Re: my if?

2003-07-02 Thread A. Pagaltzis
* Pense, Joachim [EMAIL PROTECTED] [2003-07-02 14:15]:
 You can write
 
 if ($some_condition) {
do_this;
do_that;
do_something_else;
 }
 
 and you can write
 
 do_this if $some_condition;
 
 You need not write
 
 if ($some_condition) {do_this}

You can also write


do {
do_this;
do_that;
do_something_else;
} if $some_condition;


so your second example is not really as restricted as you're
making it out to be. static() would be.

-- 
Regards,
Aristotle


Re: my if?

2003-07-01 Thread A. Pagaltzis
* Bernie Cosell [EMAIL PROTECTED] [2003-07-01 18:39]:
 Perl is filled with multiple ways to do things and the simple
 argument that you can do something similar using some other
 mechanism is rarely determinative.

...but I hesitate to make ten ways to do it. -- Larry Wall

-- 
Regards,
Aristotle


Re: grep too slow

2003-02-24 Thread A. Pagaltzis
Still untested:

* A. Pagaltzis [EMAIL PROTECTED] [2003-02-23 17:50]:
 @found3 = map pop @{$hash{$_}}, amatch('3456', @info);

That should rather read

@found3 = map shift @{$hash{$_}}, amatch('3456', @info);

The point is that the order of identical items in the
initial list is preserved in the arrays under the hash key
they get stored in. If you pull them out FIFO-fashion as you
go through the list of elements returned by amatch(), you
should get exactly what you want, in the exact same order as
if amatch() had returned the entire items.

-- 
Regards,
Aristotle


Re: grep too slow

2003-02-23 Thread A. Pagaltzis
Try this. Untested.

$t-start('transforming2');
my $i;
for(list) {
$i = $_-{'info'};
push info, $i;
push {$hash{$i}}, $_;
}
found3 = map pop {$hash{$_}}, amatch('3456', info);
$t-stop;

-- 
Regards,
Aristotle


Re: Fun with RegExps

2003-02-17 Thread A. Pagaltzis
Alternatively it can be done with negative lookaheads.

print ok if /^(?![a-z0-9]+$)(?![A-Z0-9]+$)(?![a-zA-Z]+$)[\w-]{6,14}$/;

-- 
Regards,
Aristotle



Re: When the Schwartzian Transform gets out of control...

2003-02-11 Thread A. Pagaltzis
Sorting 1000 items involves a _lot_ more than 1000
comparisons - which is really all you need.  If you insist
on your approach you should memoize vercmp() or use the
orcish maneuver in your sort() callback. (Memoizing will
accelerate it across all of your script, but the orcish
maneuvre will accelerate your callback more because it
avoids unnecessary function calls. Using both at once is
not likely to be any worthwhile optimization over simply
memoizing due to double bookkeeping though.)

But why build a list with all available versions and sorting
it, when you can discard less recent new packages right as
you build it?

You're also wasting effort in other places.

 # pkgname, ver, rel
 my @installed = map { [ /^(.*)-([^-]+)-([^-]+)$/ ] } `rpm -qa`;
 my %installed = map { $_-[0], $_ } @installed;

my %installed = map { /^(.*)-([^-]+)-([^-]+)$/ ? ($1, [$2,$3]) : ()} `rpm -qa`;

 my @available = map { [ /^((.*)-([^-]+)-([^-]+)\.[^.]+\.rpm)$/ ] } 
/a\s+href=([^]+\.rpm)/gi;

my %available;
for(/a\s+href=([^]+\.rpm)/gi) {
next unless
/^((.*)-([^-]+)-([^-]+)\.[^.]+\.rpm)$/
and exists $installed{$1}
and -1 == vercmp($2,$3, @{$installed{$_}});

$available{$1} = [$0, $2, $3]
if not exists $available{$1}
or -1 == vercmp($2,$3, @{$available{$1}}[1,2]);
}

# now printing results is trivial

print map $url/.$available{$_}[0].\n, sort keys %available;

-- 
Regards,
Aristotle



Re: When the Schwartzian Transform gets out of control...

2003-02-11 Thread A. Pagaltzis
* A. Pagaltzis [EMAIL PROTECTED] [2003-02-12 07:35]:
   and -1 == vercmp($2,$3, @{$installed{$_}});

That is, of course,

and -1 == vercmp($2,$3, @{$installed{$1}});

-- 
Regards,
Aristotle



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

2003-02-10 Thread A. Pagaltzis
* Andrew Savige [EMAIL PROTECTED] [2003-02-10 17:54]:
 *whistle* *whistle* *red card* *disqualified*
 multiplying by length (x+length) will not give the desired
 result here; it must be boolean (0 or 1 only).

Doh! Of course. I'm an idiot. *grmbl*

-- 
Regards,
Aristotle



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

2003-02-10 Thread A. Pagaltzis
* Eugene van der Pijll [EMAIL PROTECTED] [2003-02-10 18:35]:
 Unfortunately, you had use strict in your first post,
 and neither of these are use-strict safe.

Oh? What makes you say so?

-- 
Regards,
Aristotle



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

2003-02-09 Thread A. Pagaltzis
* John W. Krahn [EMAIL PROTECTED] [2003-02-09 12:27]:
 You can also speed up j1 by using map without the braces.
 
 sub j1 { my @lines = map chomp  $_, split /^/, $x, -1 }

Which will promptly fail on a last line without a trailing
record separator because chomp would return 0 and cause the
 to shortcircuit.

What you want is

sub j1 { my @lines = map scalar(chomp, $_), split /^/, $x, -1 }

-- 
Regards,
Aristotle



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

2003-02-09 Thread A. Pagaltzis
* Andrew Savige [EMAIL PROTECTED] [2003-02-10 07:28]:
   @lines = ($x=~/^.*/mg) x !!length($x);

$_=$x;@lines=(/^.*/mg)x+length;

-- 
Regards,
Aristotle



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

2003-02-07 Thread A. Pagaltzis
* Andrew Savige [EMAIL PROTECTED] [2003-02-07 13:47]:
 my @lines = split(/^/, $x, -1); chomp(@lines);  # fastest?

my @lines = split m[\Q$/], $x, -1;

-- 
Regards,
Aristotle



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

2003-02-07 Thread A. Pagaltzis
* John Douglas Porter [EMAIL PROTECTED] [2003-02-07 14:15]:
 @lines = split /\n/, $x, -1;  pop @lines;

$/ can be different from \n though. 

And popping the last field is dangerous - you don't know if
the file ends with a newline. Also, you now have no chance
to reconstruct the exact equivalent of your input using

$line = join $/, @lines;

because that will never attach a record separator to the
last line even if there was one before.

-- 
Regards,
Aristotle



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

2003-02-07 Thread A. Pagaltzis
* John Douglas Porter [EMAIL PROTECTED] [2003-02-07 14:50]:
 Yes, but his example data was text in a here document.

Then add a note about the caveat.

   split m,$/, $x, -1;

In bizarre cases, $/ might contain regex metacharacters.
Don't forget the \Q.

  And popping the last field is dangerous - you don't know if
  the file ends with a newline.
 
 You DO know it does, if the text came from a here document.

Once again; dito note caveat.

 Well, I didn't address this part of the problem, but others
 have, giving
 
   join $/, @lines, '';
 
 which is sufficient.  If you're paranoid, you can do

Not if the last line did not end with a record separator.
His example data did, but other data might not.

   join \n, @lines, $tail;

Unfortunately, that won't work either - regardless of the
value of $tail - even undef -, you are joining an extra
element onto the string.

If you really don't want that last potentially empty
element, you'll have to do something like:

my $final_recsep = $lines[-1] eq '';
pop @lines if $final_recsep;

# ...

join $/, @lines, $final_recsep ? '' : ();

-- 
Regards,
Aristotle



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

2003-02-07 Thread A. Pagaltzis
* Yitzchak Scott-Thoennes [EMAIL PROTECTED] [2003-02-07 20:51]:
 chomp(my $tmp=$x); my @lines=split /\n/,$tmp,-1

Very nice.

-- 
Regards,
Aristotle



Re: grep substitute

2002-12-14 Thread A. Pagaltzis
* Scott Wiersdorf [EMAIL PROTECTED] [2002-12-14 13:01]:
 perl -n0777
 exit !(/pattern/)
 
 Necessary Improvements:
 
 - concisely get the pattern from the command-line (e.g., pattern as
   $ARGV[0] and the file as $ARGV[1]) such that the syntax is more like
   grep (e.g., grep 'pattern' filename = perl -args 'pattern' filename)?
 
 Extra Credit:
 
 - is there a short way to do it without slurping the whole file?

perl -neexit(/$SHELLVAR/||next) file

-- 
Regards,
Aristotle



Re: my in conditionals

2002-11-27 Thread A. Pagaltzis
* Paul Makepeace [EMAIL PROTECTED] [2002-11-27 08:53]:
 perl apparently doesn't consider $d exists by the second $d and issues
 an error. Can someone explain this? (Esp. in light of all this sequence
 point talk.)

The entire statement ist compiled at a time; at this time,
$d is undeclared. The my() declaration only takes effect for
the next statement.

 for (my $i = 0; $i  10; $i++) works

Because it isn't really a for loop.

$ perl -MO=Deparse,-x7 -e'for(my $i = 0; $i  10; $i++) { }'
my $i = 0;
while ($i  10) {
();
}
continue {
++$i
}
-e syntax OK

That's why.

-- 
Regards,
Aristotle



Re: Function parameter passing (was: Re: limit the list)

2002-11-20 Thread A. Pagaltzis
* Andrew Molyneux [EMAIL PROTECTED] [2002-11-20 12:47]:
 You're not the only one.  I'd probably do:
 my ($max, $sep, $end) = @_;

aolme too/aol

  but I'd love to know if Steven had a specific reason
 for doing it the other way.

There doesn't seem to be any here.

-- 
Regards,
Aristotle



Re: Function parameter passing (was: Re: limit the list)

2002-11-20 Thread A. Pagaltzis
* Steven Lembark [EMAIL PROTECTED] [2002-11-20 17:35]:
 Yes, becuase if you did it this way you'd get $end equal
 to the integer coult of the number of list arguments passed
 plus one for the end value. Notice the usage:
 
   my $string = commify 90, ', ', 'etc...', @names;
 
 The other problem is that even if there were only three
 arguments being passed in you have to check the count
 before making the assignment and croak on @_ != 3 in
 order to avoid an extra parameter causing $end to
 become an integer count.

Enter splice.

my ($max, $sep, $end) = splice @_, 0, 3;

-- 
Regards,
Aristotle



Re: limit the list

2002-11-20 Thread A. Pagaltzis
* Steven Lembark [EMAIL PROTECTED] [2002-11-20 17:35]:
  Wasted work. Two comparisons per element and you don't bail
  once you've filled your available space.
 
 Two comparisons on a short list, at which point the remainder
 of them are a simple comparison to get a () out, which ends
 up as a null operation. And they are separate.

Still one needless comparison and null op where you could
have bailed and done nothing. May I also be so bold as to
suggest that I find this version pretty unclear - I'm quite
sure the for() approach I took breaks the task down in a way
it's instantly obvious what it's doing. And that's what I
always strive for - in this lucky case, it's more efficient
to boot.

-- 
Regards,
Aristotle



Re: limit the list

2002-11-20 Thread A. Pagaltzis
* Josh Goldberg [EMAIL PROTECTED] [2002-11-20 19:20]:
 map{$i++$lim?push @n,$_:$i!=$lim?{push @n,'etc.' and goto FOO}:''}@names;

Sigh. map in void context and goto where a for would have
done. And it doesn't even conform to the specs, you were
asked to provide a string with less than 90 characters that
should end with etc if there are more items than
displayed. As far as I can tell, all you're doing is

@n = @names[0..$lim-1];
push @n, etc if @names  $lim;

-- 
Regards,
Aristotle



Re: Function parameter passing (was: Re: limit the list)

2002-11-20 Thread A. Pagaltzis
* Steven Lembark [EMAIL PROTECTED] [2002-11-20 20:51]:
 Look up what happens to arrays in a scalar context.
 
 my ( $a, $b, $c ) = qw( foo bar bletch blort bim bam blort );
 
 what do yo get for $c?

'bletch' - and that's not an array there.

-- 
Regards,
Aristotle



Re: limit the list

2002-11-20 Thread A. Pagaltzis
* Jonathan E. Paton [EMAIL PROTECTED] [2002-11-20 20:51]:
 if (@array  $bound) {
 $array[$bound-1] = , etc; # Set element at boundary 
 $#array = $bound-1; # Shorten array to boundary
 }
 
 print join , , @array;

Again, that's the same as:

join ', ', @array[0 .. $bound], @array  $bound ? 'etc' : ();

 Now, this I *might* use in production code.  Of course, the
 obvious mistake is that space between the last element and
 the , etc part - but easily solved by using .= to append
 to the appropriate element.

No, it will look like ..blah, , etc and that's easily
remedied by using just etc since the join adds its own
,  anyway.

-- 
Regards,
Aristotle



Re: Function parameter passing (was: Re: limit the list)

2002-11-20 Thread A. Pagaltzis
* Andrew Molyneux [EMAIL PROTECTED] [2002-11-20 18:25]:
 A. Pagaltzis wrote:
  Enter splice.
 
  my ($max, $sep, $end) = splice @_, 0, 3;
 
 That has brevity, certainly, but for legibility, I think I
 prefer Steven's original (shift,shift,shift)

Really? I find the splice version a lot easier on the
easier on the eyes. But that's a matter of taste. How many
parameters do I have here?

shift, shift, shift, shift, shift, shift, shift, shift, shift, shift;
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
And this time?
splice @_, 0, 10;

Point in case, scalability.

-- 
Regards,
Aristotle



Re: limit the list

2002-11-20 Thread A. Pagaltzis
* Dave Arnold [EMAIL PROTECTED] [2002-11-21 02:45]:
 $str = join ', ', @names;
 if ( length($str)  90 )
 {
   substr($str,rindex($str,,,90)) = , etc.;
 }

Nice, and so obvious too - in retrospect, of course.

The only thing I don't like about it is it still joins
everything, even if it only needs 3 out of 10,000 elements.

-- 
Regards,
Aristotle



Re: limit the list

2002-11-19 Thread A. Pagaltzis
* Selector, Lev Y [EMAIL PROTECTED] [2002-11-20 00:55]:
 an array of names is converted into a comma-separated list.
 if the list gets to long - limit it and add , etc. at the end.

 $str = join ', ', @names;
 if (length($str)90) {
   ($str = substr($str,0,90)) =~ s/,[^,]*$/, etc./;
 }

my ($i, $total);
($total += $_)  90 or last, $i++ for map length, @names;
$str = join ',', @names[0 .. $i];
$str .= ', etc' if $i  $#names;

-- 
Regards,
Aristotle



Re: limit the list

2002-11-19 Thread A. Pagaltzis
* A. Pagaltzis [EMAIL PROTECTED] [2002-11-20 02:00]:
 my ($i, $total);
 ($total += $_)  90 or last, $i++ for map length, @names;
 $str = join ',', @names[0 .. $i];
 $str .= ', etc' if $i  $#names;

Sorry, that would of course be

($total += length) = 90 or last, $i++ for @names;

The map was left over from an earlier different approach.

-- 
Regards,
Aristotle



Re: limit the list

2002-11-19 Thread A. Pagaltzis
Ok, another attempt, this time with brain engaged and coffee
consumed.

 $str = join ', ', @names;
 if (length($str)90) {
 ($str = substr($str,0,90)) =~ s/,[^,]*$/, etc./;
 }

my ($i, $total);
($total += length)  90 ? $i++ : last for @ARGV;
$str = join ', ', @ARGV[0 .. $i];
$str .= ', etc' if $i  $#ARGV;

-- 
Regards,
Aristotle



Re: Perl Quiz of the Week

2002-10-14 Thread Aristoteles Pagaltzis

* Mark-Jason Dominus [EMAIL PROTECTED] [2002-10-13 17:48]:
 I am now back.  If you want to get the quiz-of-the-week, send a note
 to
 [EMAIL PROTECTED]
 
 Please feel free to circulate this announcement to appropriate venues.

I posted this (among others) to PerlMonks at
http://www.perlmonks.org/index.pl?node_id=204910

Someone asked if there will be web-readable mailing list
archives, to which I couldn't find an answer on the site.
Will there be?

-- 
Regards,
Aristotle



Re: Content-type:image/gif\n\n problem

2002-10-05 Thread Aristoteles Pagaltzis

* Adam Rice [EMAIL PROTECTED] [2002-10-05 23:26]:
 If I was writing this for work I would include error
 checking and read and write the file in 64k blocks, but
 there's no fun way to do that in Perl so I'll leave it out
 here.

Yes there is.

$/ = \(65536);

See perldoc perlvar on $/

-- 
Regards,
Aristotle



Re: removing extra empty lines

2002-09-30 Thread Aristoteles Pagaltzis

* Vladi Belperchinov-Shabanski [EMAIL PROTECTED] [2002-09-30 19:24]:
   $_='' if !/\S/  $e;   # i.e. don't print if empty and last one was empty
   $e = !/\S/; # remember if last one is empty...
  
  Since you have already done $_='' in the first line, you
  don't need a regex in the second to set $e. You can just say
  
  $e = !$_;
 
 line `0' will fail this test, though it is not empty line...

Doh, ack.

Assuming no warnings, I offer this:

undef $_ if !/\S/  $e;
$e = not defined;


Or assuming warnings but no undefined values:

$_= if !/\S/  $e;
$e = not length;


Ohh, may I golf?

perl -pe'!/\S/?($e++and$_=):($e=0)' filename

-- 
Regards,
Aristotle