Re: seeking golfing advice
On Wed, May 16, 2012 at 04:40:40AM -0700, John Douglas Porter wrote: And of course, use grep, as others have said. @list[ grep !$_%2, 0..$#list ]; that gets you every other element, beginning with the first. ! has higher precedence than %, so this actually gets you just the first element. You need to add parentheses to get the correct result: @list[grep!($_%2),0..$#list]; There are a couple ways to shave a character from that: @list[grep$_%2-1,0..$#list]; @list[grep$_+11,0..$#list]; Ronald
Re: decimal - Binary
On Wed, Nov 16, 2011 at 04:14:57PM +0100, Olof Johansson wrote: On 2011-11-16 09:57 -0500, Ronald J Kimball wrote: That should be s/0*//, otherwise you'll get the wrong result for numbers above 2147483647. That should be s/^0*//, otherwise you'll get the wrong result for numbers above 2147483647. No, you are wrong. s/0*// is sufficient, because /0*/ will always match at the start of the string anyway. Ronald
Re: decimal - Binary
On Wed, Nov 16, 2011 at 07:49:14PM +0100, Olof Johansson wrote: On 2011-11-16 11:57 -0500, Ronald J Kimball wrote: No, you are wrong. s/0*// is sufficient, because /0*/ will always match at the start of the string anyway. You're clearly an expert. I yield. Can you open a bug report with perl and getting this fixed? It's working as expected for me, so I'm not sure what needs to be fixed. % cat tmp.pl #!perl -l print$_: ,($_=unpackB*,packN,$_)=~s/0*//?$_:$_ for@_=@ARGV; print$_: ,($_=unpackB*,packN,$_)=~s/^0*//?$_:$_ for@_=@ARGV; % perl tmp.pl 2147483648 30 2147483648: 1000 30: 1011001011010100 2147483648: 1000 30: 1011001011010100 % Are you seeing different behavior? Ronald
Re: decimal - Binary
On Wed, Nov 16, 2011 at 09:34:58PM +0100, Olof Johansson wrote: On 2011-11-16 14:14 -0500, Ronald J Kimball wrote: It's working as expected for me, so I'm not sure what needs to be fixed. Hum, now I'm ashamed. Sorry. But why is that not greedy? (I got other results earlier, but I can't reproduce now so I have probably made an error in my earlier attempts.) It is greedy, but the important thing to remember is that the regular expression engine will find the longest *leftmost* match. For example, 00111000 =~ /0*/ will match (00)111000. It won't match (0)0111000, because, although it's a leftmost match, it's not the longest leftmost match. And it won't match 00111(000) because that's not a leftmost match, regardless of the length. Ronald
Re: code line of the day
On Thu, Sep 07, 2006 at 07:21:07AM -0700, Randal L. Schwartz wrote: Uri == Uri Guttman [EMAIL PROTECTED] writes: Uri @{$self-{templates}}{ keys %{$tmpls} } = Uri map ref $_ eq 'SCALAR' ? \${$_} : \$_, values %{$tmpls} ; Uri discuss amongst yourselves. topics include: what does it do? Uh, it throws a lot of warnings when values(%$tmpls) has non-references? What do I win? Why would it throw warnings? ref() returns empty string if the argument isn't a reference. Ronald
Re: /$sudoku/
I presented Ilmari's /$sudoku/ scripts at the Boston.pm meeting last week. During the discussion, we thought of a further optimization. Ilmari's first version uses a generic regular expression. The second version hardcodes the known values into the negative-lookahead assertions. The optimization we came up with is to apply the known values directly in the target string. For example, if we know that an empty spot can't be 3, 5, or 9, then that line in the target string will be 124678. I also made the regex even more specific to the puzzle, although that probably doesn't have a noticeable effect on the speed. This version will solve puzzles in about half the time as the second version. However, it does move farther away from the concept of solving the puzzle with a regex, as more work is being done outside the regex. I still like the purity of Ilmari's first version of the script! Anyway, here's the code: #!/usr/bin/perl -w use strict; while (defined(my $input = )) { chomp $input; length($input) != 81 || $input =~ tr/1-9_//c and (print(Bad input.\n), next); $input =~ tr/_/0/; my $sudoku = '^'; my $string; foreach my $n (0 .. 80) { if (my $d = substr($input, $n, 1)) { $string .= $d\n; $sudoku .= ($d)\n; } else { $sudoku .= '.*'; my @skip; my $digits = '123456789'; foreach my $m (grep $_ != $n (int($_ % 9) == int($n % 9) || int($_ / 9) == int($n / 9) || int($_ / 27) == int($n / 27) int($_ / 3 % 3) == int($n / 3 % 3)), 0..80) { if (my $e = substr($input, $m, 1)) { $digits =~ s/$e//; } elsif ($m $n) { push @skip, \\ . ($m + 1); } } if (@skip) { $sudoku .= '(?!' . join('|', @skip) . ')'; } $string .= $digits\n; $sudoku .= (.).*\n; } } $sudoku .= '$'; print((join(, $string =~ /$sudoku/) || No solution.), \n); } __END__ Ronald
Re: Interesting little regex
On Fri, Feb 24, 2006 at 01:40:15PM -0700, Alan Young wrote: Yes, what are the unique occurrences of text in that string? I've run the code and I'm still not exactly sure what it's supposed to do. use Data::Dump qw/ dump /; $a=abcdex4; $a=~s{((\w+?)(??{!$b{$^N}++?(?=):(?!)}))}{($1)}xg; print $a\n; print dump(\%b), \n; (a)(b)(c)(d)(e)(ab)(cd)(ea)(bc)(de)(abc)de { a = 3, ab = 2, abc = 1, b = 2, bc = 1, c = 2, cd = 1, d = 3, de = 2, e = 3, ea = 1 } There is 1 unique occurrence of 'abc', 2 occurrences of 'ab' (not contained in the other occurrence of 'abc'), and 3 occurrences of 'a' (not contained in the other occurrences of 'abc' and 'ab'). I'm afraid I'm not getting what you mean by unique occurrence... Why is there only one unique occurrence of 'abc', when the string contains 'abc' four times? Why are there two unique occurrences of 'de', but only one of 'bc'? Why are there no unique occurences at all of 'abcd'? I just thought it was a neat little regex that qualified as a FWP and pass it along to my perl monger and user groups as well. It is a neat regex, that's why I want to understand what it's for. :) Ronald
Re: Interesting little regex
On Fri, Feb 24, 2006 at 03:20:27PM -0700, Alan Young wrote: I'm afraid I'm not getting what you mean by unique occurrence... Why is there only one unique occurrence of 'abc', when the string contains 'abc' four times? Why are there two unique occurrences of 'de', but only one of 'bc'? Why are there no unique occurences at all of 'abcd'? I'm probably not stating myself well (I'm known for that). Maybe unique occurrence isn't what I'm really trying to say. If we have a stream of text (say we have a file that is several 10s of million bytes in size) and we're limited to how much we can load into memory at a time, or we're recieving it over a connection of some kind (e.g., serial or tcp) and we have a varying number of delimiters, with a varying delimiter length (delimiter1, delim2, del3). The value of the delimiter is the delimiter and an unspecified number of bytes, up to the next known delimiter. (value of delimiter 'del2' in the string 'del1abcdel2def' is 'del2def'. I don't understand exactly why this format was decided upon, this was the poser handed to my co-worker and this is what he came up with as a proof of concept. Of course, this requires that no delimiter can be a substring of another. Better? It's making more sense now. Thank you for taking the time to explain it to me! Ronald
Re: A curious logic
On Tue, Mar 08, 2005 at 08:50:11AM -0500, Perl Diety wrote: ...are easy and IMO, not interesting... juxtapositioned with , but I never found one... Vern or Vernette, doesn't this imply that either: (a) You didn't look very hard, since being easy, they should also be easy to find or (b) They are not so easy? or (c) you quoted out of context and misunderstood the original post. ...regexes that match themselves _and also other strings_ are easy and IMO, not interesting... [my emph] ...I was looking for a regex matching itself - _and nothing but itself_, ... but I never found one. [my emph] The two phrases which you quoted are describing _different_ classes of regular expressions. Ronald
Re: Shortening a script, but aiming for efficiency
On Fri, Oct 01, 2004 at 09:23:14AM -0600, Alan Young wrote: a\tb\t a\t\t \tb\t \t\t\t The output for all these should be: a|b a|\s |b |\s This means that I could start by replacing all tabs with pipes, but then I would always have to remove the last pipe... I could replace two ending pipes with | (second and fourth cases), but I would also have to remove a single ending pipe (first and third cases) Then use a '+': s/\|+$/ /; That's not the desired behavior either. Look at the examples above. Ronald
Re: Load-Bearing Warnings
On Tue, Aug 03, 2004 at 06:12:25PM +, Smylers wrote: I turned warnings off in a script[*0] but made no other changes to it. This broke the script, in that it would no longer run correctly[*1]. In other circumstances[*2] I might've regarded this as fun. Presuming that this isn't a well-known situation, can anybody guess how it's done? Does the script use $SIG{__WARN__}? Ronald
Re: Another regexp conundrum
On Tue, Jun 01, 2004 at 02:11:56PM -0400, [EMAIL PROTECTED] wrote: 13 '__pqrxyz__pqr___abc___' =~ /(($re).*?)*(?!)/; Of course, this is incomplete, but it is a start. One thing that puzzles me is that the (?!) is absolutely required on line 13. Without it, @seen doesn't get initialized at all. Why should this be? I would have thought that the final '*' in the regexp would be enough to get the regexp to continue attempting to match. /(anything)*/ can always match a zero length substring at the beginning of the string, and as soon as the regex engine finds a match, it stops. The (?!) forces the regex engine to backtrack through all possible matches. Ronald
Re: Another regexp conundrum
On Tue, Jun 01, 2004 at 05:22:01PM -0400, [EMAIL PROTECTED] wrote: /(anything)*/ can always match a zero length substring at the beginning of the string, and as soon as the regex engine finds a match, it stops. The (?!) forces the regex engine to backtrack through all possible matches. I can see how that would be the case if the modifier were *?, but with plain * I expect the engine to match greedily, and not stop at the first match. Emphasis: *at the beginning of the string*. Without the (?!), your regex matches zero occurences of $re at the beginning of the string. The regex engine always finds the longest, *leftmost* match. (Where longest really means with the least backtracking.) Ronald
Re: fractional cents
On Mon, Apr 26, 2004 at 06:49:52AM +0200, Pense, Joachim wrote: A. Pagaltzis [mailto:[EMAIL PROTECTED] wrote: 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.. But then you still have the issue of marking the difference between 257 cents and 257.0 cents. Of course. But that's much better than marking the difference between 2.57 dollars and 2.56984013 dollars, wouldn't you agree? Ronald
Re: lwall snippet
On Sun, Apr 11, 2004 at 12:06:17AM -0400, [EMAIL PROTECTED] wrote: I see. But I think you meant $_ x= /(..:..)...(.*)/ 'foo' ge $1 'foo' lt $2; since the shell's $2 is never used, as far as I can tell. I still have no clue what the shell's $1 would be in this case, other than the empty string. % cat tmp.sh last|perl -pe '$_ x=/(..:..)...(.*)/'$1'ge$1'$1'lt$2' % ./tmp.sh 12:00 rjk console rojeki.local.Sat Apr 10 11:59 still logged in rjk console rojeki.local.Sat Mar 27 11:38 - 12:31 (00:53) rjk console rojeki.local.Sat Mar 13 09:19 - 23:14 (13:54) rjk console rojeki.local.Sun Dec 7 10:21 - 22:44 (12:22) Ronald
Re: pattern finding problem
On Tue, Mar 09, 2004 at 01:43:05PM -0500, Ronald J Kimball wrote: I think I've got almost what you want. It correctly limits the length and number of repetitions (example 1) and handles overlapping occurrences of the pattern (example 2). The one flaw is that it will only match one possible substring starting at any point in the string. For example, if you have S = ABAB, P = [AB], A = 2, B = 4, C = 2, D = 4, you could match ABAB, ABA, and AB all at the start of the string, but my regex will only match ABAB (example 3). Perl won't match a 0-length substring more than once at the same position. I'm not aware of a simple way around that within the regex. Here's a fairly simple way to avoid the flaw, but that breaks out of the regex mold. Instead of returning the results from the match (potentially one at a time), the regex in this solution pushes the matches directly onto a results array. The regex engine will find all the matches with a single execution of the regex, because the regex uses (?!) to force backtracking even after what would be a successful match. With this code, example 3 gives all six possible matches instead of just three. #!/usr/local/bin/perl -w use strict; use re 'eval'; my @args = ( [qw/ ABCBAB [AB] 3 3 2 2 /], [qw/ 12121212 1212 8 8 3 3 /], [qw/ ABAB [AB] 2 4 2 4 /], ); foreach my $args (@args) { print @$args\n; my @matches = subpattern(@$args); foreach my $match (@matches) { print @$match , substr($args-[0], $match-[0], $match-[1] - $match-[0]), \n; } print \n; } sub subpattern { my($string, $pattern, $minlen, $maxlen, $minrep, $maxrep) = @_; my $not_pattern = (?:(?!$pattern).); my $match_length = (?{(length\$1=$minlenlength\$1=$maxlen) . [EMAIL PROTECTED],[\$-[0],\$-[0]+length\$1]}); my @matches; my $re = (?=($not_pattern* . ((?=$pattern).$not_pattern*){$minrep,$maxrep} . )$match_length(?!)); warn $re\n; $string =~ /$re/; return @matches; }
Re: lvalue hash slice
On Tue, Sep 30, 2003 at 11:07:24PM +0300, Gaal Yahas wrote: I like hash slices: ($one, $two, $three) = @hash{ qw/aaa bbb ccc/ }; Sadly, this doesn't work as an lvalue: @hash{ qw/aaa bbb ccc/ } = ($one, $two, $three);# WRONG That actually does work. Ronald
Re: I know this is not fun.
On Thu, Jul 17, 2003 at 09:31:31AM +0100, Moran, Matthew wrote: Gareth wrote: How about a perl filter to strip all non-fwp posts to this list? Depends on one's definition of fun I guess - some might say it's perl programs that are whimsical in some way like the Camel script, or a well-obfuscated japh, whereas some might say it's a really meaty problem that we can get our teeth into and toss about until we get an elegant solution. I hope most of this list's members would agree that this list is not intended to be a help desk. There are already plenty of other forums that fill that need. Ronald
Re: my if?
On Tue, Jul 01, 2003 at 05:15:09PM +0300, Vladi Belperchinov-Shabanski wrote: my $id = 1 if $_ == 3; my has a compile time behavior and a runtime behavior. At compile time, my allocates memory for the variable and adds it to the pad. At run time, my resets the value of the variable. If you put a conditional on the my statement, then the run time behavior does not occur when the conditional is false. Instead of getting reset, the value is preserved from the previous iteration. 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. Ronald
Re: reencoding ampersands for html, longhand
On Wed, Apr 02, 2003 at 10:25:05PM -0600, [EMAIL PROTECTED] wrote: Anyway, I got all the named entities (the numbered ones aren't a problem), created a hash: %html_entities = ( quot = 1, amp = 1, lt = 1, gt = 1, nbsp = 1, ... [ 200 more entities ] and came up w/: sub clean_html { my $string = shift; my @ents = split(//, $string); The use of split seems an odd choice. I would try doing this as a substitution with /e. Then, using a lookahead, all that needs to be replaced is the ampersand. Here's one way to do it: s/(?=(\w{2,7});|#(\d{3});|)/ my $replace; if ($1 and exists $html_entities{$1}) { # named entity $replace = ''; } elsif ($2) { # numeric entity $replace = ''; } else { # not an entity $replace = 'amp;'; } $replace; /ge; Ronald P.S. If you wanted to golf it, perhaps something like this, with %html_entities renamed to %h: $='|';s/([EMAIL PROTECTED];|#\d{3};)/amp;/g; Of course, @h would be even better in this case. :)
Re: golf tee puzzle
On Thu, Mar 13, 2003 at 01:22:26PM -0800, Quantum Mechanic wrote: I came at it from another direction, starting out caching the board state (equivalent to @state) for each board seen. [In most cases, there are several paths to a given board state.] I also used some other speedups, like precomputing the jump neighbors for each hole, and computing all rotations/reflections of each board and caching all of them (there are 5 equivalents for each board state, besides itself). The problem space soon blows up rather large for larger board sizes. For instance, I've seen it run out of memory on a large machine (caching boards) for N=7 (7 pegs on a side, 28 holes total), having cached about 1M boards. Since the rotations/reflections are equivalent, you could save a lot of memory by only caching a canonical instance of each board state. For example, number the holes with powers of 2, and only cache the rotation/reflection with the lowest sum of occupied holes. Of course, checking the cache would also require finding the canonical state, so you would be saving memory by adding runtime. Ronald
Re: correctly rebuilding a whitespace-split string
On Tue, Oct 15, 2002 at 04:08:41AM +, Ton Hospel wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] writes: En op 15 oktober 2002 sprak Aaron Mackey: @d = splice(split, -4); # I always know that the last 4 fields This won't compile (first argument to splice must be an array). # this next line is the one to focus on: $str = join(, (split(/(\s+)/, $_, scalar(@d) + 1))[0..2*$#d]); method 2: ($str) = m/^(\S+(?:\s+\S+){$#d})/; @d = (split)[-4..-1];# @d contains last 4 fields for later use s/(?:\s+\S+){4}\s*$//; # $_ now contains required string /-\ /\S+/g;//;//;//;// # $` now contains required string Unfortunately, this solves the wrong problem. It gets the first four pieces of the string, instead of all but the last four. I think this approach would work to get the desired string in $`: /(\s+\S+){4}\s*$/; Ronald
Re: NPL Puzzler for 6 Oct
On Fri, Oct 11, 2002 at 02:54:20PM -0400, Bernie Cosell wrote: The NPL puzzle for 6 oct was an interesting little Perl exercise [I'm not sure how to solve it analytically --- I played with it some to little avail --- but it was certainly subject to brute force, and it turned out to be a cute little thing. Write out the digits from 1-9 in order. Then add some plus (+) signs and times (x) signs to the string to make it add up to 2,002. As usual in arithmetic, multiplication is done before addition, and you don't have to put a sign between every 2 digits. The answer is unique. What's odd is that my little Perl program found *TWO* solutions, but one is potentially ambiguous [in particular, given those rules, what should the value of a*b*c be?-- it doesn't say whether things should be done left-to-right or right-to-left, so perhaps that could be used to exclude one of the two solutions. It doesn't matter whether the multiplication is evaluated left-to-right or right-to-left, because multiplication is associative. The product is the same either way. Anyhow, here's the little program I whipped up for it... the fun part is that it is one of the rare times that counting base-3 is useful: for (my $count = 0; $count 3**8; $count += 1) { my $try = fixstr($count) ; print $try,\n if eval($try) == 2002 ; } exit ; sub fixstr { my $key = $_[0] ; my $str = 123456789 ; for (my $i = 8; $i 0; $i -= 1) { my $next = $key % 3 ; $key = int($key/3) ; next unless $next ; substr ($str, $i, 0, $next == 1? '+': *) ; } return $str ; } Obviously I'm not a golfer, but I'm wondering if there are any other interesting approaches to the problem... [base-3 and eval seemed pretty clean/cute to me] There was discussion of this puzzle on the Boston.pm mailing list as well. The thread starts at http://mail.pm.org/pipermail/boston-pm/2002-October/000160.html Ronald
Re: Perl Challenges, Anywhere?
On Fri, Aug 30, 2002 at 11:58:03AM -0500, James Edward Gray II wrote: Could anyone point me in the direction of a Perl challenge/contest that's not Obfuscation or Golf? I've done some heavy searching but come up empty handed. Are you looking for an ongoing contest to participate in, or a past contest to research? Other kinds of Perl contests include the Perl Death Bowl (TPC 3), and Perl Poetry. Ronald
Re: Perl Challenges, Anywhere?
On Fri, Aug 30, 2002 at 12:31:19PM -0500, James Edward Gray II wrote: Forgive my ignorance, but what is the Perl Death Bowl or TCP 3, for that matter? TPC 3 was The Perl Conference 3.0. (This year's conference was TPC 6.0.) One of the events at TPC 3 was a sort of competitive programming challenge called the Perl Death Bowl. Two programmers, going head-to-head in front of the audience, had a limited amount of time to write a certain program. There were some technical glitches, but it went off fairly well. The best part was Chris Nandor and Chip Salzenburg providing color commentary. I was mostly asking from the ongoing contest to participate in, but failing that or in addition to it, past contests would be more than I have now. I would love to test my Perl skills a bit, but low readability just isn't my thing. Thanks for your time and help. Another good place to look would be PerlMonks: http://www.perlmonks.org/ Ronald
Re: removing extra empty lines
On Mon, Aug 12, 2002 at 01:28:19PM -0400, Selector, Lev Y wrote: Folks, I have a long file which has many empty lines with nothing but may be spaces or tabs (/^\s*$/). These lines tend to group together creating chunks of empty vertical space on the printout. I want to reduce the number of empty lines in such chunks to 1 line. What would be an elegant way to do this? perl -p0377i -e 's/^\s*$//gm' Ronald
Re: Non-head, non-tail recursion???
On Fri, Aug 02, 2002 at 02:28:01PM -0500, [EMAIL PROTECTED] wrote: To understand recursion, we must first understand recursion. Thereby demonstrating tail recursion quite nicely, as distinct from GNU's Not Unix which demonstrates (presumably) head recursion. Can you think of an acronym or saying that demonstrates non-head, non-tail recursion? There's a Dilbert cartoon in which Dilbert decides his project needs an official sounding acronym. He names it The TTP Project. TTP stands for The TTP Project. Ronald
Re: a little shorter please?
On Mon, Jul 22, 2002 at 02:41:25PM -0400, Aaron J Mackey wrote: I can't seem to get this any shorter: I want the second through the next-to-last elements of F joined by , and then the last item of F. perl -ape '$,= ;s//F[1..$#F-1]\n$F[$#F]/' or (no join, but same general idea): perl -pe 's/\s+(\S+)$/\n$1/;s/^\S+\s+//;' What trick am I missing? Your regexes are unnecessarily verbose. :) perl -pe 's/\S+$/\n$/;s/\S+\s+//' Ronald
Re: reading lines backwards
On Tue, Jun 11, 2002 at 12:18:42PM -0400, Selector, Lev Y wrote: Folks, Problem: need to read a very big text file starting from the end and moving backwards to its beginning. This is similar to a diamond ( FH ) operator functionality - but in the opposite direction. Need to do it without reading and reversing the array of lines for the whole file (which would be the obvious solution for a short file). Any suggestions? http://search.cpan.org/search?dist=File-ReadBackwards Ronald
Re: FW: shortest test for truth false assignment
On Wed, May 22, 2002 at 03:58:05PM -0400, Patrick Gaskill wrote: $a($a=0)||do{do_something()}; Anyway, the second bit of code there will short-circut after the first expression if $a is false, so everything after $a won't get executed, leaving $a alone. But has higher precedence than ||, so do_something() will get executed whether or not $a is false. Ronald
Re: shortest test for truth false assignment
On Wed, May 22, 2002 at 10:45:39PM +0100, Simon Cozens wrote: Scott Wiersdorf: if( $a%2 .. $a-- ) { I don't understand this. You see, if $a-- leaves $a as false, then: if ($a--) is the shortest way of solving the problem. But that will change $a to true if it was false. Here's what I understand the goal to be: If $a is true, set $a to false and execute some code If $a is false, do nothing. Ronald
Re: shortest test for truth false assignment
On Wed, May 22, 2002 at 10:55:52PM +0100, Simon Cozens wrote: Ronald J Kimball: if( $a%2 .. $a-- ) { Here's what I understand the goal to be: If $a is true, set $a to false and execute some code But the code above doesn't do that for all true values. Sorry, I left out a condition. You can choose what values to use for true and false. (As implied in the original message, It doesn't have to be numeric (i.e., bit strings or any true/false values will work).) Ronald
Re: shortest test for truth false assignment
On Wed, May 22, 2002 at 09:54:52PM -0400, Yanick wrote: On Wed, May 22, 2002 at 10:06:39PM -0400, Josh Goldberg wrote: I came up with another one. This also works for values of true other than 1. if ($a=~tr/.[^0]+/0/c) { do_something(); } s/tr/s/, maybe ? (the transliterate operator doesn't use patterns, so the code above change every instances of '.' by a 0, of '[' by a '[' and so on and so forth...) Actually, it translates every character that is *not* one of '.[^0]+' into '0'. /c complements the search list. When the search list is longer than the replacement list, the last character in the replacement class is repeated. Ronald
Re: First differing char in two strings
On Thu, Apr 25, 2002 at 12:51:33PM -0500, Craig S. Cottingham wrote: A: craigc@samantha craigc $ perl -e '$a = 1; print +(--$a + $a++) . \t$a\n' 1 1 B: craigc@samantha craigc $ perl -e '$a = 1; print +($a + $a++) . \t$a\n' 3 2 C: craigc@samantha craigc $ perl -e '$a = 1; print +(--$a + $a) . \t$a\n' 0 0 D: craigc@samantha craigc $ perl -e '$a = 1; print +($a++ + - --$a) . \t$a\n' 2 1 E: craigc@samantha craigc $ perl -e '$a = 1; print +($a + - --$a) . \t$a\n' 0 0 F: craigc@samantha craigc $ perl -e '$a = 1; print +($a++ + $a) . \t$a\n' 3 2 B and F make sense, if you assume that B is commuted to F internally. C and E make sense, if you assume that E is commuted to C internally. I can't figure out why A and D evaluate differently, nor why A evaluates to 1 instead of 0 as I'd expect. The results of C, D, and F suggest that perl, at least in this instance, evaluates the operands to the '+' binary operator in left-to-right order. Post-decrement and -increment leave a copy of the variable's current value on the stack, and then change the value of the variable. Pre-decrement and -increment change the value of the variable and then leave a *pointer to that variable* on the stack. In the latter case, the value of the variable may change before the pointer is retrieved from the stack. FYI, this particular behavior has been discussed extensively on various forums. Ronald
Re: First differing char in two strings
On Thu, Apr 11, 2002 at 05:06:28PM -0400, Prakash Kailasa wrote: On Thu, Apr 11, 2002 at 05:03:53PM -0400, Jeff 'japhy' Pinyan wrote: On Apr 11, Prakash Kailasa said: On Thu, Apr 11, 2002 at 08:06:14AM -0700, Paul Makepeace wrote: The task is to find the first differing character given two strings. There is one obvious solution walking along using substr, ($a^$b)=~y/\0// That isn't helpful, though -- that merely gives a count of how many characters were the same between the two. We need the position of the first difference. Hmm, wasn't the example given by Paul (original poster) giving the same value? ($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. Ronald
Re: Why bother with separate lists?
On Mon, Mar 25, 2002 at 11:19:37PM +0100, Philippe 'BooK' Bruhat wrote: On Mon, 25 Mar 2002 [EMAIL PROTECTED] wrote: But is this the official perl-golf mailing list? Or is Ronald or someone else going to create a new [EMAIL PROTECTED] and change the charter of [EMAIL PROTECTED]? Why do we need to have perl twice in the same address? [EMAIL PROTECTED] seems self-explanatory... I just remembered that there is already a [EMAIL PROTECTED] mailing list. :) It was created to plan and organize the Perl Golf Apocalypse at TPC 4. Perhaps Uri would be willing to open it up for general use. Ronald
Re: Why bother with separate lists?
On Tue, Mar 19, 2002 at 10:27:47PM -0500, Bernie Cosell wrote: Oh, please. If it took a minute to download *all* 143 messages I'd be surprised. Yes, I know that some folk do pay by the byte but minimizing- bytes has hardly been a hallmark of the postings to the list... [thinking here of the HUGE ascii-art hackery, and all of the postings on the first golf tournament probably didn't add up to as much traffic as that picture of Larry or Randal or whoever it was, or that 'banner program'] You seem to have a very poor grasp of the numbers involved. Byte count by thread: ASCII Randal 36964 bytes Banner JAPH 82522 bytes Middle Line golf214736 bytes Santa Claus golf548360 bytes Human Sort golf 72582 bytes Get Even golf 382016 bytes TPR0 golf 265586 bytes TPR1 golf 333081 bytes fun for *some* of us, so keep it on fwp, just be careful with subject some being the keyword. I'd say that because it's fun for only *some* of us, a separate list is in order. Oh please, again. There is *NO* topic that is 'fun' for everyone. No other topic swamps all other traffic on this mailing list. It is quite reasonable that if a specific sub-topic appeals to only some of the subscribers but accounts for most of the traffic on a list, that sub-topic should be spun off into its own list. I suspect that some folk didn't find the discussion of Perl 6's breaking printf strings very much fun, so maybe we need a separate list for 'perl syntax discussions'. Perhaps you missed it, but the printf thread *was* declared off-topic by the list-mom. It would have been appropriate, as you suggest, on a Perl6 syntax mailing list, which already exists. And then there's the ASCII-art stuff, and the JAPH's (is it obligatory, by your reckoning, that everyone finds JAPHs fun?); and then there's the detailed discussions of the side effects of little-known variables, and... Probably with a little work we could divide fwp up into 20 separate focused fun sublists... some fun. Dividing fwp up into 20 separate focused fun sublists would be foolish, because 19 of those subtopics each account, individually, for a small part of FWP's traffic. I say keep it as one list and have folk learn to use the machinery their mail clients provide them with; that's why mail clients HAVE that machinery. I say create a new Perl Golf list, especially for the involved discussion of golf tournaments. (Much like comp.lang.perl.modules was spun off of comp.lang.perl.misc, especially for the discussion of modules.) While I agree that it is *possible* for people to deal with excessive traffic by creating filters, killing threads, and so on, I just don't see why that solution is *better* than creating a new list. Ronald
Re: Golf contests and naive solutions?
On Sun, Mar 17, 2002 at 10:00:47AM +0100, Jerome Quelin wrote: Hi folks, We were wondering if the referees were to provide a naive solution for perlgolf contests? This way, beginners could really see what the script is to do (remember Ton's Christmas tournament where only one beginner managed to provide a working solution - and thus, won). Otoh, I can imagine golf holes where such a solution would be too much a hint... In general, yes, a naive solution should be given for a Perl golf contest. The main purpose in providing a solution is not to give hints, but to make it clear what the actual challenge is. For example, the human sort challenge was incompletely specified, even after several attempts, and would have benefited greatly from an example solution. For more suggestions on formulating a golf challenge, see my post Tips on Writing a Golf Challenge on PerlMonks: http://www.perlmonks.org/index.pl?node_id=82470 Ronald
Re: Perl Golf as a sport
On Mon, Mar 11, 2002 at 12:31:25PM +1100, [EMAIL PROTECTED] wrote: I know, from bitter experience with Acme::EyeDrops, just how flaky the (?{}) construct is; normally you cannot use regular expressions inside it at all because Perl's regex engine is not reentrant. And yet, mysteriously, the s///eg construct seems exempt from this not rentrant rule. I do not understand. Look more closely: s/pattern1/s,pattern2,replacement,ge/ge; The second substitution is part of the *replacement* for the first substitution, not part of the pattern. Thus, when the regex engine is working on pattern2, it is not working on pattern1, and vice versa; there's no reentering going on. Ronald
Re: TPR1 post-mortem
On Fri, Mar 08, 2002 at 10:33:26AM +, Piers Cawley wrote: Stephen Turner [EMAIL PROTECTED] writes: On Fri, 8 Mar 2002 [EMAIL PROTECTED] wrote: Here are some statistics from the current series of games: fwp Santa (head, tail, ...):35 players on scoreboard irc Christmas (human sort): 11 players on scoreboard fwp Get Even: 51 players on scoreboard TPR Base 36:82 players on scoreboard TPR Secret Number: 128 players on scoreboard This reminds me of something. I'd love to know more about the history of Perl golf. Who invented it, and so on. Does anyone know about this? (And if so, would it make a good article for TPR? :-) Not sure who invented it, but this http://groups.google.com/groups?selm=7km3p5%24gm6%244%40info2.uah.eduoutput=gplain appears to be where the term was coined by Greg Bacon. Actually, I think it was this one from Greg Bacon, a month earlier: http://groups.google.com/groups?hl=enselm=7imnti%24mjh%241%40info2.uah.edu Ronald
Re: TPR1 post-mortem
On Fri, Mar 08, 2002 at 12:04:15PM +0100, F.Xavier Noria wrote: On Fri, 08 Mar 2002 11:41:31 +0100 cizaire_liste [EMAIL PROTECTED] wrote: : Can someone explains me why : : my $c = '($a=www)=~s{}{z}g;print $a\n;die'; : eval $c; : $^O=~s{.}{$c}ee; : : output two lines that are different ? : ($^O is only used to have a not empty string) I have not studied it carefully, but at first sight I see a possible gotcha, when the pattern is {} s uses the last successful pattern that matched (this is surely imprecise or false, I have not the Camel book here), just to throw an idea. Nice work, that is the correct explanation. The first time $c is evaled in the code snippet, there is no previous successfully matched pattern, so s{}{z}g matches the null string at every position in $a. When $c is evaled inside s{.}{$c}ee, the pattern /./ was just successfully matched, so s{}{z}g matches /./. This shows the same behavior: ($a=www)=~s{}{z}g; print $a\n; $a =~ /./; ($a=www)=~s{}{z}g; print $a\n; Ronald
Re: TPR1 post-mortem
On Fri, Mar 08, 2002 at 03:16:10PM +0100, Marcelo E. Magallon wrote: A question of my own: why doesn't s/\B.\B/$$/g work as I expect, namely abcd - abbccd. I really can't figure it out by reading the docs. It works as expected in perl5.005_3 and perl5.7.2. There are many subtle bugs in the regex engine in perl5.6.0 and perl5.6.1. Ronald
Re: interesting typo I couldn't see
On Sun, Feb 17, 2002 at 12:02:49PM -0500, Bill -OSX- Jones wrote: Vicki writes: if (...) { my @item_parts = split(/\n/, $item); printf ORDER (\n%4d %-50s %3.2f %3.2f\n, $quantity, $item_parts[0], $price, $ext); } else { printf ORDER (\n%4d %-50s %3.2f %3.2f\n, } $quantity, $item, $price, $ext); That last line there has the } out of sequence; should be: printf ORDER (\n%4d %-50s %3.2f %3.2f\n, $quantity, $item, $price, $ext); } Oops! The problem I noticed is that the output columns won't line up. :) Ronald
Re: Longest Common Substring
On Fri, Feb 15, 2002 at 07:27:03AM -0600, Tim Ayers wrote: A == Andrew Pimlott [EMAIL PROTECTED] writes: A On Fri, Feb 15, 2002 at 01:37:15AM -0500, Jeff 'japhy' Pinyan wrote: Except that you are forced to find a 2-character match, which means you end up skipping a POTENTIAL 3-character-or-more match. A Due to the while loop, we will keep looking for longer matches. A Otherwise, your version would have a similar bug, finding earlier, A shorter matches. No offense, but did you try it without the comma? It doesn't work. If you get a 2-character match, the regex engine gains a new starting point for the 3-character match. Thus throwing away the 2 characters that just matched. If they are part of the lcs, you just lost part of your answer. It does work, if you drop the comma *and* the /g modifier, so that it starts searching at the beginning of the string each time. Ronald
Re: TPR0 Final Results
On Sat, Feb 16, 2002 at 11:10:41AM +1100, [EMAIL PROTECTED] wrote: Stephen Turner wrote: Can someone explain to me why -l use POSIX;print strtol pop,36 doesn't work? Where does the extra 0 come from? To quote myself to Dave and Jerome: BTW, because I felt you were already inundated with queries about it, I did not bother you with what seems to be a Perl bug that prevents a 32-stroke solution from working. I was too lazy to analyse it (instead, I trusted that Ton would, but since he has not posted 32, I guess it cannot be worked around). #!/usr/bin/perl -l use POSIX;print strtol pop,36 I think this should work, but it prints a spurious trailing zero. RTFM. strtol String to (long) integer translation. Returns the parsed number and the number of characters in the unparsed portion of the string Ronald
Re: Finding Holidays
On Thu, Feb 07, 2002 at 12:19:01AM -0500, Bill -OSX- Jones wrote: Hi :) I was asked recently if I could write a Perl program that would find out when the next time Christmas day would actually be on a Sunday. #!perl use Date::Christmas qw/ christmasday /; for my $year (1900 .. 2100) { print Christmas found on a Sunday in $year if christmasday($year) eq 'Sunday'; } __END__ :) Ronald
Re: More Wacky Solutions
On Thu, Jan 31, 2002 at 05:28:15PM +0100, [EMAIL PROTECTED] wrote: One can get as close to 0.833 as one wants, by writing something like: $=ss; and adding as many 's's after the = as needed to obtain the desired ratio. $ is readonly; how about $ss; Ronald
Re: A present ...
On Thu, Jan 24, 2002 at 12:31:51PM -0500, Bill -OSX- Jones wrote: 69 strokes - #!perl -n next if(($.%2)||(((length)-1)%2));!((tr/aeiouy//)%2) and print$_; #!perl -n next if(($.%2)||(((length)-1)%2));print$_ unless((tr/aeiouy//)%2); But ... Still prints even sets of vowels :( -Sx- Please review the rules for this golf event: Please take care to not accidentally post any solutions to the fwp mailing list!! Do not publish your solutions anywhere. That will spoil the game, as your solutions are meant to be secret. All solutions will be published at the end of the game. Ronald
Re: match URI and nothing more?
On Tue, Jan 22, 2002 at 08:59:51AM -0800, Big D wrote: Bill, This is commonly referred to as 'leaning toothpick syndrome' (LTS). The problem is that you're using / as your regex delimiter AND you're not escaping it in your regex. Change your delimiter to something NOT in your regex, like @ or or whatever, i.e. @:http://.@ is a valid regex (Perl is smart about this). When Perl produces the error message, the regex is delimited with slashes regardless of the actual delimiter used in the code. Note that the error message in this case shows slashes within a regex delimited by slashes: /:http://(/ BTW, using balanced characters, e.g. m{} or s[][], is often the best way to delimit complicated regular expressions. Ronald
Re: make a 24(another practical problem)
On Fri, Jan 18, 2002 at 10:27:14AM -0600, Greg Bacon wrote: In message [EMAIL PROTECTED] one.net, user who writes: Enumerating the possible operator layouts: - # # o # o # o - # # o # # o o - # # # o o # o - # # # # o o o where '#' represents a number and 'o' an operator. A little combinatorics: 4! # positions for numbers 4# number of operations x 4# number of operator layouts --- 384# size of search space Each operator position can hold one of four operators, which means you have 4**4 different arrangements of operators for each of the four operator layouts. 4! * (4**4) * 4 = 24576 Ronald
Re: Practical Perl Problem
On Mon, Jan 14, 2002 at 11:01:57PM -0500, Aaron D. Marasco wrote: At 22:54 14 01 2002, Ronald J Kimball wrote: On Mon, Jan 14, 2002 at 07:32:15PM -0500, Aaron D. Marasco wrote: The double hyphen in front of the incoming text is optional and could have spaces on either side of it. The spaces between fields is arbitrary (but never tabs). The signal fields always have at least one space on the left, Is that in addition to the space after the double hyphen? it is required to make sense. After all, these are comments we are parsing, and it is wise to have the signals indented under what they are for... I'll take that as a yes. Are there any kinds of lines besides comments and signal fields? Well, the rest of the code, but I have no problem with cut paste of the script out of the VHDL comments and then cutting that block out of the code. Okay, as long as it doesn't need to be accounted for in our solutions. The overall length of the script is the most important, speed is no concern. Lines are limited to 78 characters too. :( Four lines: #!perl -nl s/^ ?-- ?//;push@a,[s/:$//?--== $_ ==--:/^ *(\S+)\s+(\S+)\s*(\S*)/]; $;=$:if($:=length$1)$;}{*b=$_,$#b?($b[2]=~s/.+/_vector($ downto 0)/, $b[2]=~s/^/ std_logic/,printf%-$;s : %s%s;\n,@b):print@b for@a OK, let's see if I can figure this one out... I think s/^[ -]*//; would beat s/^ ?-- ?//; wouldn't it? As long as you're confident in the formatting of your input. As far as I know there may be lines that start with '- -' or something like that. After that, I cannot keep track anymore of what is going on. :( Okay, the annotated version... :) #!perl -nl # while () { # chomp; ## from -n s/^ ?-- ?//; # remove the leading double hyphen, if present. push @a, [ s/:$// ? --== $_ ==-- : /^ *(\S+)\s+(\S+)\s*(\S*)/ ]; # push an anonymous array onto @a # if $_ ends with a colon (which is removed), the anonymous array # contains the string --== $_ ==-- # otherwise, the anonymous contains the three substrings matched by # /^ *(\S+)\s+(\S+)\s*(\S*)/ $; = $: if ($:=length$1) $; # if the length of $1 is greater than $; # then assign the length of $1 to $; # $; will hold the maximum length of $1 over all the lines } ## # while () { { *b=$_, # assign the array reference in $_ to *b # now @b is the same array as @$_ $#b ? ( $b[2]=~s/.+/_vector($ downto 0)/, $b[2]=~s/^/ std_logic/, printf%-$;s : %s%s;\n,@b ) : print @b # if @b does not have exactly one element # then do some substitutions on the third element of @b # and print out the formatted string with the elements of @b # otherwise just print the contents of @b for @a # do all that for each element in @a # } ## { ## from -n Ronald
Re: Practical Perl Problem
On Mon, Jan 14, 2002 at 10:54:28PM -0500, Ronald J Kimball wrote: #!perl -nl s/^ ?-- ?//;push@a,[s/:$//?--== $_ ==--:/^ *(\S+)\s+(\S+)\s*(\S*)/]; $;=$:if($:=length$1)$;}{*b=$_,$#b?($b[2]=~s/.+/_vector($ downto 0)/, $b[2]=~s/^/ std_logic/,printf%-$;s : %s%s;\n,@b):print@b for@a __END__ P.S. As demonstrated by Schwern's solution, my second substitution on $b[2] is, of course, unnecessary. #!perl -nl s/^ ?-- ?//;push@a,[s/:$//?--== $_ ==--:/^ *(\S+)\s+(\S+)\s*(\S*)/]; $;=$:if($:=length$1)$;}{*b=$_,$#b?($b[2]=~s/.+/_vector($ downto 0)/, printf%-$;s : %s std_logic%s;\n,@b):print@b for@a __END__ Ronald
Re: Golf challenge: decode CETI message
On Sun, Jan 13, 2002 at 03:41:40AM +0200, Ilmari Karonen wrote: On Fri, 11 Jan 2002, Philip Newton wrote: On Wed, 9 Jan 2002 20:34:30 -0500, [EMAIL PROTECTED] (Keith C. Ivey) wrote: But s'\x0\xff' @' to make it shorter and more visible on my system. y(s))y) ? qBut y'\x0\xff' @' to make it yhorter and more viyible on my yyytem. ? Besides, aren't single quotes special for s/// and y/// anyway? I think what Keith _really_ meant was tr[\0\xff][ @] or equivalent. I think what Keith *really* meant was not, use s'\x0\xff' @' in the code, but rather, run s'\x0\xff' @' *on* the code, i.e. change the 7 character sequence to the two character sequence. The use of single quotes is deliberate. He's looking at the output of the code in ASCII, rather than converting the output to an actual image. Ronald
Re: Interactive golf hole
On Tue, Jan 08, 2002 at 02:50:16PM -0500, Jeff 'japhy' Pinyan wrote: On Jan 8, Yitzchak Scott-Thoennes said: 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 ':'. My code is below. Those solutions don't quite work, because they include the surrounding double quotes as part of the field in the output. According to the description, the surrounding quotes are not part of the actual field. Ronald
Re: Interactive golf hole
On Tue, Jan 08, 2002 at 11:50:44AM -0800, Yitzchak Scott-Thoennes wrote: Also, I said: Fields are separated by 1 or more whitespace characters, so xx is one 4 character field, not two 1 character fields. Woops, I got that part wrong. Gotta go rework my solution... Ronald
Re: Interactive golf hole
On Tue, Jan 08, 2002 at 01:30:12PM -0800, Yitzchak Scott-Thoennes wrote: 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. 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. Ronald
Re: Perl and majordomo
On Wed, Dec 26, 2001 at 04:46:11PM -0500, Michael G Schwern wrote: On Wed, Dec 26, 2001 at 01:24:20PM -0800, Sir Not-appearing-in-this-film wrote: Someone should write a working 'unsubscribe' function in Perl for Majordomo mailing lists. The current system does not seem to work. perl.org mailing lists don't use Majordomo. They're... something else. ezlm? mailman? Look at the full mail headers on this and all perl.org list messages. List-Post: mailto:[EMAIL PROTECTED] List-Help: mailto:[EMAIL PROTECTED] List-Unsubscribe: mailto:[EMAIL PROTECTED] List-Subscribe: mailto:[EMAIL PROTECTED] Mailing-List: contact [EMAIL PROTECTED]; run by ezmlm :) Ronald
Re: test a password string for correctness
On Thu, Dec 13, 2001 at 03:24:14PM +0100, Sven Neuhaus wrote: On Thu, Dec 13, 2001 at 03:01:43PM +, Mohit Agarwal wrote: On Thu, Dec 13, 2001 at 02:49:05PM +0100, Sven Neuhaus wrote: y/A-Za-z/A-Za-z/2y/0-9/0-9/1 or the shorter $a=$_;y/A-Za-z//2y/0-9//1 that will mungle the password in $_ but keep a good copy in $a. Why will it mungle the password in $_ ??? It won't - I was confusing it with the behavior of some tr programs. So it's y/A-Za-z//2y/0-9//1 y/A-Za-z//2y/0-9//1 Ronald
Re: test a password string for correctness
On Thu, Dec 13, 2001 at 08:36:03AM -0600, [EMAIL PROTECTED] wrote: If you are prepared to change $_: if (y/a-zA-Z//2y/0-9//1) {# 24 chars for the test print not valid; } That does not change $_. If you can't change $_, you need the c opt on the y's, hence: if (y/a-zA-Z//c2y/0-9//c1) { # 26 chars for the test print not valid; } That does not change $_ either; /c complements the search class, so the first translation counts the occurences of non-letter characters, and the second translation counts the occurences of non-digit characters. When the replacement class is empty, and /d is not specified, then the search class is used as the replacement class as well. Ronald
Re: test a password string for correctness
On Thu, Dec 13, 2001 at 10:41:57AM -0500, Jeff 'japhy' Pinyan wrote: I probably would have thought about y/// after a while, but I can't pass up a good regex. ;) y/a-zA-Z//2y/0-9//1 is probably where I'd get to. I think RJK's attempt to cheat the system fails: y/a-zA-Z//y/0-9//1 fails for 4 and 3 (0100 0011 == 0). That is NOT what I posted. This is the solution I posted: y/a-zA-Z//2y/0-9//1 Or, more readably: (y/a-zA-Z// 2) (y/0-9// 1) Each numeric comparison will return either 1 or 0. The bitwise-and will return true if and only if both numeric comparisons return true. Ronald
Re: test a password string for correctness
On Thu, Dec 13, 2001 at 07:11:09PM -0500, Ryan Fischer wrote: I guess it simply wasn't good that the guy asked a question on an FWP list where TMTOWTDI and so many people think the short ways are better. If he was simply looking for an answer, any other list would have worked fine. I guess you've already forgotten what the guy actually asked: How short kan you make a program (oneliner?) that... He posted to FWP intentionally looking for the shortest possible answer, which is exactly what we provided. I really don't understand why you're being so insulting to the other members of this list. Ronald
Re: Possible improvements for the next golf apocalypse
On Sun, Dec 09, 2001 at 12:31:06PM +1100, [EMAIL PROTECTED] wrote: However, I suggest that in future games the Arbiter should reveal the leading scores for each hole about 4-8 hours from the end. This should make the final hours quite exciting. I think that 4-8 hours is too short, considering that people may be participating from around the world. It should be at least 16 hours, to give everyone a chance to work with the new information. Ronald
Re: Possible improvements for the next golf apocalypse
On Mon, Dec 10, 2001 at 04:36:26PM +0100, BooK wrote: En réponse à [EMAIL PROTECTED]: IMHO a solution to a good hole should be in the 50-70 char region. That way there's more scope for styling the response. Such styling could include: - the least number of /a-z/i chars. - the largest number of times a chosen bonus character is used - inefficiency of the algorithm My particular favourite is how sorted the code is $code=for(0..9)print; @chars = map {ord($_)} split //, $code; for ($x=0; $x+1 @chars;$x++) { $score++ if ($chars[$x]$chars[$x+1]); } print $score You mean (supposing the code is in $_, and $score is in $s): $o=\xff;for(split//){$s++if($_$o);$o=$_};print$s Mmm. This might not work (or compile): I do not have a perl here. (I tried other things to obfuscate the algorithm, and then I remembered I was at work. Oops.) You're using a numeric comparison on strings. :) $s+=$lt$1while/.(?=(.))/gs;print$s Ronald
Re: The Santa Claus Golf Apocalypse
On Mon, Dec 03, 2001 at 08:49:33PM +, Piers Cawley wrote: Ronald J Kimball [EMAIL PROTECTED] writes: Why would printing to STDERR warrant a penalty anyway? It should disqualify the entry entirely. On what grounds? Nothing was mentioned when the challenge was set except that we weren't supposed to use die to output stuff, which is emphatically not what I'm doing. Similarly, your programs must properly newline-terminate everything they write (they always write to stdout). In my mind, the idea of perl golf is to write code with certain semantics in as few characters as possible, by changing the syntax. If you change the semantics to get fewer characters, then you're solving a different problem. Ronald
Re: Daily Perl FAQ - How do I select a random line from a file? (fwd)
On Thu, Nov 29, 2001 at 06:36:06AM +0100, Philip Newton wrote: On Wed, 28 Nov 2001 12:46:06 -0600, [EMAIL PROTECTED] (Andy Bach) wrote: Thanks much. I thought there might be related technique for getting a rand element from an array, but we know the array length so ... this (from above) did help w/ my getting all the elements in a random order, i.e.: while ( @arr ) { $pos = rand($#arr); $val = splice @arr, $pos, 1; print is: $val\n; } Obi-Wan error in there? I think you need rand(@arr), or you're never going to get the last element (since rand($#arr) always is $#arr). Actually, the last element will always come out last, because rand(0) is the same as rand(1). Ronald
Re: middle line (was Re: Daily Perl FAQ...)
On Thu, Nov 29, 2001 at 11:34:24AM -0800, Chris Thorpe wrote: On Thu, 29 Nov 2001, Yanick wrote: On Thu, Nov 29, 2001 at 01:34:02PM -0500, Michael G Schwern wrote: Yesterday, I saw an interesting related exercise. Write a program that reads the lines from a file and outputs the middle line. The kicker is that you can't use arrays. I'll interpret that as O(1) memory, O(n) time. You can't do it in O(1) memory and O(n) time. There's a time/memory tradeoff. At line m, you have to store m/2 lines in memory if you use O(n) time, if the file stops anywhere between m and m*2 (which you don't know.) If you elect to use O(1) memory, then you have to use O(1.5*n) time, as the already submitted examples do. O(1.5*n) time is O(n) time. Constant factors are irrelevant in Big-O notation. Ronald
Re: Practical Perl Golf
On Thu, Nov 15, 2001 at 07:42:41AM -0500, Keith C. Ivey wrote: Jeff 'japhy' Pinyan [EMAIL PROTECTED] wrote: perl -pe's/^\s*#(?!\s*((ifn?|un)def|(el|end)?if|define|include|else)\ b).*//s' Note that without the /s modifier, . will NOT match the trailing \n, so I'd have to add \n to the end of the regex, adding a character to the count. An alternative would be to use the -l switch in place of the /s modifier. That strips off the newline on input and puts it back on on output. That will not work in this case, because it would print out a newline for every line of input, including the ones that are being skipped. Ronald
Re: World's Largest JAPH
On Thu, Sep 13, 2001 at 12:12:09PM +1000, [EMAIL PROTECTED] wrote: The step 2 program uses a conversion module called Filth. I have no CPAN experience, and am open to suggestion, but this module might eventually become CPAN Convert::Filth (??). I'd suggest Acme::Filth, to go with Acme::Bleach and Acme::Buffy. Interestingly, I had to change: $x =~ s/\S/#/g; to $x =~ tr/!-~/#/; because the former caused the generated Perl program to malfunction in strange ways. I guess because the whole program is running inside a regex, there are some limitations on what the source program can do. Yes, Perl's regex engine is not re-entrant. It can't execute a new regex in the middle of executing another regex. Ronald P.S. That's just sick.
Re: evaluating assigning to a list in if( ) statement
On Mon, Sep 03, 2001 at 09:35:13PM -0400, Lev Selector wrote: # Folks, just a note. # I thought that the #if (EXPR) # is supposed to evaluate the EXPR in scalar context, right? # Well, it does so in most cases # Except when you do an assignment to a list, when # instead of evaluating a list as its last element - it evaluates # the number of elements (like an array) (see Example_5 below). # This is probably what you would want to test (if list empty or not) # # Any comments? perldoc perldata: List assignment in a scalar context returns the number of elements produced by the expression on the right side of the assignment: $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2 $x = (($foo,$bar) = f()); # set $x to f()'s return count This is very handy when you want to do a list assignment in a Boolean context, because most list functions return a null list when finished, which when assigned produces a 0, which is interpreted as FALSE. Ronald
Re: Japhs by SMS.
On Thu, Aug 09, 2001 at 04:17:36PM -0500, David L. Nicol wrote: Jeff 'japhy/Marillion' Pinyan wrote: Why not: 0=~(?\173\LPRINT\E'J\LUST ANOTHER\E P\LERL\E H\LACKER\12'\175); 65 chars. Wow. Why does binding this string to 0 cause it to get evald? It's a regular expression match. \173 and \175 are curly braces, so the regex includes the (?{ }) syntax mentioned earlier. You can use any expression as a regular expression with the binding operator. For example: print Yay!\n if 4 =~ 2+2; Ronald