[25525] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 7769 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Feb 11 00:05:45 2005

Date: Thu, 10 Feb 2005 21:05:16 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Thu, 10 Feb 2005     Volume: 10 Number: 7769

Today's topics:
    Re: [perl-python] combinatorics fun <eppstein@ics.uci.edu>
    Re: [perl-python] combinatorics fun axel@white-eagle.invalid.uk
    Re: [perl-python] combinatorics fun <yyusenet@yahoo.com>
    Re: [perl-python] combinatorics fun <tanghaibao@gmail.com>
    Re: FAQ 7.3 Do I always/never have to quote my strings  <martin.gregory@freescale.com>
        Is there a more idiomatic way to do this? <amead@comcast.net>
    Re: Lexical scoping question. <michael+gnus@trollope.org>
    Re: opening a file to read and write ioneabu@yahoo.com
    Re: opening a file to read and write <jurgenex@hotmail.com>
    Re: opening a file to read and write ioneabu@yahoo.com
    Re: opening a file to read and write <1usa@llenroc.ude.invalid>
    Re: opening a file to read and write ioneabu@yahoo.com
    Re: rename captures in regex <toddrw69@excite.com>
    Re: rename captures in regex <skuo@mtwhitney.nsc.com>
    Re: rename captures in regex ioneabu@yahoo.com
    Re: rename captures in regex <toddrw69@excite.com>
        track how many moves to sort an array? <gj@freeshell.org>
    Re: track how many moves to sort an array? <sbryce@scottbryce.com>
    Re: track how many moves to sort an array? <toddrw69@excite.com>
    Re: track how many moves to sort an array? <jurgenex@hotmail.com>
    Re: track how many moves to sort an array? <jurgenex@hotmail.com>
    Re: track how many moves to sort an array? <sbryce@scottbryce.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Thu, 10 Feb 2005 15:35:56 -0800
From: David Eppstein <eppstein@ics.uci.edu>
Subject: Re: [perl-python] combinatorics fun
Message-Id: <eppstein-3833FA.15355610022005@news.service.uci.edu>

In article <1108075884.250995.62520@g14g2000cwa.googlegroups.com>,
 "Xah Lee" <xah@xahlee.org> wrote:

> combo(n) returns a collection with elements of pairs that is all
> possible combinations of 2 things from n. For example, combo(4)
> returns {'3,4' => ['3',4],'1,2' => [1,2],'1,3' => [1,3],'1,4' =>
> [1,4],'2,3' => ['2',3],'2,4' => ['2',4]}; Hash form is returned
> instead of array for this program.

def combo(n):
    return dict([('%d,%d'%(i,j),(i,j))
                 for j in range(n) for i in range(j)])

import pprint
pprint.pprint(combo(5))


output:

{'0,1': (0, 1),
 '0,2': (0, 2),
 '0,3': (0, 3),
 '0,4': (0, 4),
 '1,2': (1, 2),
 '1,3': (1, 3),
 '1,4': (1, 4),
 '2,3': (2, 3),
 '2,4': (2, 4),
 '3,4': (3, 4)}


Note I'm using 0-based indexing, use range(1,n+1) and range(1,j+1) 
instead if you really need it to be 1-based.

Also I'm using Python 2.3, I think in 2.4 you can take out the square 
brackets and it would still work.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/


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

Date: Thu, 10 Feb 2005 19:25:45 -0600
From: axel@white-eagle.invalid.uk
Subject: Re: [perl-python] combinatorics fun
Message-Id: <yK6dnST8KN8ElJHfRVn-1A@adelphia.com>

In comp.lang.perl.misc Xah Lee <xah@xahlee.org> wrote:
> a year ago i wrote this perl program as part of a larger program.
 
> sub combo ($) {
>    my $max=$_[0];
>    my %hh=();
>    for (my $j=1; $j < $max; ++$j) {
>        for (my $i=1; $i <= $max; ++$i) {
>            my $m = (($i+$j)-1)%$max+1;
>            if ($i < $m){ $hh{"$i,$m"}=[$i,$m];}
>        }
>    }
>    return \%hh;
> }
 
Well, it's not obfuscated Perl. It is, however, an obfuscated algorithm.

Sane people would use something along the lines of:

sub combo {
    my $max = shift;
    my %hh=();
    for my $i ( 1 .. $max ) {
        for my $j ( $i + 1 .. $max ) {
            $hh{"$i,$j"} = [$i, $j];
        }
    }
    return \%hh;
}

 
Axel



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

Date: Thu, 10 Feb 2005 19:15:18 -0700
From: YYUsenet <yyusenet@yahoo.com>
Subject: Re: [perl-python] combinatorics fun
Message-Id: <cuh4fq$p2l$1@news.xmission.com>

Xah Lee wrote:
> a year ago i wrote this perl program as part of a larger program.
> 
> as a exercise of fun, let's do a python version. I'll post my version
> later today.
  [code snipped]
> 
> This is Perl-Python a-day. To subscribe, see
> http://xahlee.org/perl-python/python.html
> 
> Xah
> xah@xahlee.org
> http://xahlee.org/PageTwo_dir/more.html
> 

Why are you posting this to comp.lang.python? This obviously has nothing 
to do with python at all.  If you are trying to teach people python, 
claiming that "...let's do a python version. I'll post my version later 
today."  Isn't really the proper way to do it.  An even better method 
would be to set up a website dedicated to nothing but it, and stop 
posting here with garbage code that no one wants to read, and that helps 
no one.  Please, consider others a little bit when you go off on your 
wild hope that you might be able to teach other people what you 
obviously know nothing about, teaching people from a language that you 
know nothing about.   *PLEASE STOP POSTING*!! *NOBODY WANTS YOU TO POST*!!

-- 
yyusenet (at) xmission (dot) com


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

Date: 10 Feb 2005 20:19:54 -0800
From: "Haibao Tang" <tanghaibao@gmail.com>
Subject: Re: [perl-python] combinatorics fun
Message-Id: <1108095593.988957.22550@c13g2000cwb.googlegroups.com>

I am no longer resisting. As time goes, the nausea when I first saw Mr.
Lee's smelly "technical posts" is starting to fade. The discussion
group should have a high tolerance towards polymorphic people these
days.



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

Date: Fri, 11 Feb 2005 14:15:31 +1030
From: Martin Gregory <martin.gregory@freescale.com>
Subject: Re: FAQ 7.3 Do I always/never have to quote my strings or use semicolons and commas?
Message-Id: <cuh9o5$173$1@az33news01.freescale.net>

PerlFAQ Server wrote:
> This message is one of several periodic postings to comp.lang.perl.misc
> intended to make it easier for perl programmers to find answers to
> common questions. The core of this message represents an excerpt
> from the documentation provided with Perl.
> 
> --------------------------------------------------------------------
> 
> 7.3: Do I always/never have to quote my strings or use semicolons and commas?
> 
>     Normally, a bareword doesn't need to be quoted, but in most cases
>     probably should be (and must be under "use strict"). But a hash key
>     consisting of a simple word (that isn't the name of a defined
>     subroutine) and the left-hand operand to the "=>" operator both count as
>     though they were quoted:
> 
>         This                    is like this
>         ------------            ---------------
>         $foo{line}              $foo{"line"}
>         bar => stuff            "bar" => stuff
> 

Why do we use "" when '' will do?

Isn't "" more work for perl (since it has to look to see if it
needs to interpolate)?


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

Date: Thu, 10 Feb 2005 23:04:56 -0600
From: Alan Mead <amead@comcast.net>
Subject: Is there a more idiomatic way to do this?
Message-Id: <pan.2005.02.11.05.04.55.844672@comcast.net>

I recently created a script that did a lot of this sort of thing:

my $dataref = get_data($filename1) if ($condition==1);
my $dataref = get_data($filename2) if ($condition==2);

foreach my $datum (keys %$dataref) { ...

Which didn't raise an exception but $dataref was always nil.  I had to
write:

my $dataref;
$dataref = get_data($filename1) if ($condition==1);
$dataref = get_data($filename2) if ($condition==2);

I'm not sure I understand precisely why the first one didn't work but
also failed to raise an error when run under the strict pragma.  I
mean, if it was a scoping thing then shouldn't the reference to
%$dataref in the foreach loop trigger an exception?  

Anyway, the second method fixed the problem but it's a bit ungainly. Is
there a more idiomatic way to do this?  

Thanks,

-Alan

-- 
Come get a free personality profile:
http://www.web-data-collection.org



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

Date: 10 Feb 2005 22:45:08 -0500
From: Michael Powe <michael+gnus@trollope.org>
Subject: Re: Lexical scoping question.
Message-Id: <uoeeru5dn.fsf@trollope.org>

>>>>> "Louis" == Louis  <louis@despammed.com> writes:

    Louis> Hi, The below script will print "var is apple". I find this
    Louis> weird, because in textbooks you are taught to pass variable
    Louis> to subroutines as parameters. What is the point of doing
    Louis> this, if the variable is visible anyway?

    Louis> How can I make the variable exist in main and yet be
    Louis> invisible to the subroutine? I know I can create another

Use 'anonymous' blocks.  Any variable declared with 'my' outside a
block has file scope.  To permit the variable only a local scope, put
it in a block like this:

c:\src>type test.pl
type test.pl
#!perl

use strict;

{
my $var = "string";

}

print $var;

c:\src>test.pl
test.pl
Global symbol "$var" requires explicit package name at C:\src\test.pl line 10.
Execution of C:\src\test.pl aborted due to compilation errors.

I use these blocks for encapsulating variables all the time.  Helps
protect me from myself.  ;-)

In python, btw, it is a common idiom to define a main() function in
your script, which serves the same purpose of maintenance of scope.

mp

-- 
Michael Powe		michael@trollope.org		Waterbury CT
ENOSIG:	signature file is empty


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

Date: 10 Feb 2005 16:48:01 -0800
From: ioneabu@yahoo.com
Subject: Re: opening a file to read and write
Message-Id: <1108082881.226389.103880@f14g2000cwb.googlegroups.com>

Tad McClellan wrote:

>
> The "normal" place to run Perl programs is from the command line,
> that is what most people will assume unless you tell them otherwise.
>

Which 'command line' is standard?

Most or all Unix shells will be the same with respect to Perl but not
the Windows command line, at least regarding quoting.

What about double-clicking on icon from GUI of various OS's?

You are right that I should specify how I am invoking my scripts.

wana



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

Date: Fri, 11 Feb 2005 01:25:56 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: opening a file to read and write
Message-Id: <EQTOd.19048$uc.12342@trnddc08>

ioneabu@yahoo.com wrote:
> Tad McClellan wrote:
>> The "normal" place to run Perl programs is from the command line,
>> that is what most people will assume unless you tell them otherwise.
>>
>
> Which 'command line' is standard?

Doesn't really matter, pretty much any will do.

> Most or all Unix shells will be the same with respect to Perl but not
> the Windows command line, at least regarding quoting.

But that's not a Perl issue. Once you've figured out how to get the quoting 
(or file pathes or whatever for that matter) right for your OS and command 
line shell, then from there on it's all the same. And the Perl part starts 
only at the "from there on".

> What about double-clicking on icon from GUI of various OS's?

Well, why would you want to?

jue 




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

Date: 10 Feb 2005 19:22:59 -0800
From: ioneabu@yahoo.com
Subject: Re: opening a file to read and write
Message-Id: <1108092179.445838.283300@z14g2000cwz.googlegroups.com>


Tad McClellan wrote:

> The "normal" place to run Perl programs is from the command line,
> that is what most people will assume unless you tell them otherwise.
>
>

Forget any other example I have given.  Here is a perfect one:  I
cannot execute my Perl programs from the command line under Cygwin
unless they have the proper shebang line.  That is definitely a
standard way to execute a perl program and it is different from
executing from the command line provided by Windows were the OS
determines the type of file by the extension.

wana



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

Date: Fri, 11 Feb 2005 03:51:21 GMT
From: "A. Sinan Unur" <1usa@llenroc.ude.invalid>
Subject: Re: opening a file to read and write
Message-Id: <Xns95F9E880CFE88asu1cornelledu@127.0.0.1>

ioneabu@yahoo.com wrote in news:1108092179.445838.283300
@z14g2000cwz.googlegroups.com:

> 
> Tad McClellan wrote:
> 
>> The "normal" place to run Perl programs is from the command line,
>> that is what most people will assume unless you tell them otherwise.
> 
> Forget any other example I have given.  Here is a perfect one:  I
> cannot execute my Perl programs from the command line under Cygwin
> unless they have the proper shebang line.  

You were originally changing the shebang lines to 

#!/c:/perl/bin/perl.exe

which is a monstrosity.

So, I am assuming the original files had unixy shebang lines, maybe:

#! /usr/bin/perl

or similar.

If you are using the Cygwin environment, then you should use the Perl 
distribution built for that environment, in which case, the second 
shebang line above would work without modification.

Regardless of distribution, I cannot really see the point of changing 
shebang lines to first version when you are on a Windows computer. 
Either you have the ActiveState or a similar distribution in which case 
the shebang line is not relevant to locating the perl executable, or you 
have the Cygwin distribution which is almost exactly like being on a 
unixy system.

Sinan


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

Date: 10 Feb 2005 20:07:21 -0800
From: ioneabu@yahoo.com
Subject: Re: opening a file to read and write
Message-Id: <1108094841.361119.300570@c13g2000cwb.googlegroups.com>


A. Sinan Unur wrote:
 ...
> Regardless of distribution, I cannot really see the point of changing

> shebang lines to first version when you are on a Windows computer.
> Either you have the ActiveState or a similar distribution in which
case
> the shebang line is not relevant to locating the perl executable, or
you
> have the Cygwin distribution which is almost exactly like being on a
> unixy system.
>
> Sinan

That's probably the problem.  I am using ActiveState only, yet I
sometimes work with Cygwin where I do not have the Cygwin Perl
distribution installed, so I have to call on ActiveState Perl there
too.

The problem is that I prefer a Unix-like environment, yet Windows
supports the hardware on my laptop much better than any version of
Linux (Suse does the best though).  My next computer will certainly be
an OS X laptop when this one fails and/or I can afford it.

I will definitely take your advice on the registry changes to fix the
problem with executing my cgi scripts.

wana



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

Date: Fri, 11 Feb 2005 00:21:27 GMT
From: "Todd W" <toddrw69@excite.com>
Subject: Re: rename captures in regex
Message-Id: <bUSOd.3532$ng6.793@newssvr17.news.prodigy.com>


"Gunnar Hjalmarsson" <noreply@gunnar.cc> wrote in message
news:3725eeF56gmm6U1@individual.net...
> Todd W wrote:
> > A factory function we have makes some stupid assumptions about the data
it
> > is parsing. I give it content and a regex, and it gives me back an
array.
> >
> > Is there any way, for example, to tell capture 1 of a regex to store its
> > value in $2?
>
> Not that I know of.
>
> But if the function returns an array, and you want to print it in some
> other order, can't you just do:
>
>      my @array = qw/bar foo bazz/;
>      printf "One:\n  title: %s\n  link:  %s\n  descr: %s\n",
>        @array[2,0,1];
>
The function sticks the data in a db before it gets returned. Imagine the =~
and print in a function. Hence the requirement in my post that ony the value
of the $reg2 var could be changed to make the program work for me.

The developer provided a hook so you could bypass the default mechanism and
write your own, which is what I used, but I was just wondering if anyone
knew offhand how to do what I asked in the original post.

Thanks anyway,

Todd W.




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

Date: Thu, 10 Feb 2005 19:14:29 -0800
From: Steven Kuo <skuo@mtwhitney.nsc.com>
Subject: Re: rename captures in regex
Message-Id: <Pine.GSO.4.21.0502101906550.15946-100000@mtwhitney.nsc.com>

On Thu, 10 Feb 2005, Todd W wrote:

> A factory function we have makes some stupid assumptions about the data it
> is parsing. I give it content and a regex, and it gives me back an array.
> 
> Is there any way, for example, to tell capture 1 of a regex to store its
> value in $2?
> 
> Here is the output of the program below.
> 
> [trwww@waveright misc]$ perl cap.pl
> One:
>   title: bar
>   link:  foo
>   descr: bazz
> Two:
>   title: bazz
>   link:  bar
>   descr: foo
> 
> Is there any way to make the output of "One:" identical to the output of
> "Two:" by changing ONLY the the string stored in $reg2?



In genernal, no.


>
> use warnings;
> use strict;
> 
> my $str1 = '<a href="foo">bar</a><div>bazz</div>';
> my $reg1 = '<a href="([^"]+)">([^<]+)</a><div>([^<]+)<';
> 
> $str1 =~ m|$reg1|;
> 
> print("One:
>   title: $2
>   link:  $1
>   descr: $3
> ");



You really should check whether the match succeeded before printing
$1, etc.


> my $str2 = '<div>bar</div><div>bazz</div><a href="foo">readmore</a>';
> 
> ### modify only this regex
> my $reg2 = '<div>([^<]+)</div><div>([^<]+)</div><a href="([^"]+)"';
> 
> 
> $str2 =~ m|$reg2|;
> 
> print("Two:
>   title: $2
>   link:  $1
>   descr: $3
> ");



In this specific case, you could try this (the lookahead pattern):

my $str2 = '<div>bar</div><div>bazz</div><a href="foo">readmore</a>';
my $reg2 = qr!(?=.*?</div><a href="([^"]+)")<div>([^<]+)</div><div>([^<]+)</div>!;

if ($str2 =~ /$reg2/) {
    print <<""
Two
  title: $2
  link:  $1
  descr: $3

}


-- 
Hope this helps,
Steven



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

Date: 10 Feb 2005 20:18:38 -0800
From: ioneabu@yahoo.com
Subject: Re: rename captures in regex
Message-Id: <1108095518.553809.61610@o13g2000cwo.googlegroups.com>


Todd W wrote:
> A factory function we have makes some stupid assumptions about the
data it
> is parsing. I give it content and a regex, and it gives me back an
array.
>
> Is there any way, for example, to tell capture 1 of a regex to store
its
> value in $2?
>
> Here is the output of the program below.
>
> [trwww@waveright misc]$ perl cap.pl
> One:
>   title: bar
>   link:  foo
>   descr: bazz
> Two:
>   title: bazz
>   link:  bar
>   descr: foo
>
> Is there any way to make the output of "One:" identical to the output
of
> "Two:" by changing ONLY the the string stored in $reg2?


>
> use warnings;
> use strict;
>
> my $str1 = '<a href="foo">bar</a><div>bazz</div>';
> my $reg1 = '<a href="([^"]+)">([^<]+)</a><div>([^<]+)<';
>
> $str1 =~ m|$reg1|;
>
> print("One:
>   title: $2
>   link:  $1
>   descr: $3
> ");
>
> my $str2 = '<div>bar</div><div>bazz</div><a href="foo">readmore</a>';
>
> ### modify only this regex
> my $reg2 = '<div>([^<]+)</div><div>([^<]+)</div><a href="([^"]+)"';
>
>
> $str2 =~ m|$reg2|;
>

Sorry if I'm not getting the problem, but it seems that this would do
it:

my ($title, $link, $descr) = ($1, $3, $2);

 print("Two:
   title: $title
   link:  $link
   descr: $descr
 ");


wana



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

Date: Fri, 11 Feb 2005 04:32:04 GMT
From: "Todd W" <toddrw69@excite.com>
Subject: Re: rename captures in regex
Message-Id: <8zWOd.3608$ng6.3287@newssvr17.news.prodigy.com>


"Steven Kuo" <skuo@mtwhitney.nsc.com> wrote in message
news:Pine.GSO.4.21.0502101906550.15946-100000@mtwhitney.nsc.com...
> On Thu, 10 Feb 2005, Todd W wrote:
>
> > A factory function we have makes some stupid assumptions about the data
it
> > is parsing. I give it content and a regex, and it gives me back an
array.
> >
> > Is there any way, for example, to tell capture 1 of a regex to store its
> > value in $2?
> >
> > Here is the output of the program below.
> >
> > [trwww@waveright misc]$ perl cap.pl
> > One:
> >   title: bar
> >   link:  foo
> >   descr: bazz
> > Two:
> >   title: bazz
> >   link:  bar
> >   descr: foo
> >
> > Is there any way to make the output of "One:" identical to the output of
> > "Two:" by changing ONLY the the string stored in $reg2?
>
> In genernal, no.

Thats okay, considering what you provided below

> >
> > use warnings;
> > use strict;
> >
> > my $str1 = '<a href="foo">bar</a><div>bazz</div>';
> > my $reg1 = '<a href="([^"]+)">([^<]+)</a><div>([^<]+)<';
> >
> > $str1 =~ m|$reg1|;
> >
> > print("One:
> >   title: $2
> >   link:  $1
> >   descr: $3
> > ");
>
> You really should check whether the match succeeded before printing
> $1, etc.

It happens in the actual function. What I posted was just for demonstration.

> > my $str2 = '<div>bar</div><div>bazz</div><a href="foo">readmore</a>';
> >
> > ### modify only this regex
> > my $reg2 = '<div>([^<]+)</div><div>([^<]+)</div><a href="([^"]+)"';
> >
> >
> > $str2 =~ m|$reg2|;
> >
> > print("Two:
> >   title: $2
> >   link:  $1
> >   descr: $3
> > ");
>
> In this specific case, you could try this (the lookahead pattern):
>
> my $str2 = '<div>bar</div><div>bazz</div><a href="foo">readmore</a>';
> my $reg2 = qr!(?=.*?</div><a
href="([^"]+)")<div>([^<]+)</div><div>([^<]+)</div>!;
>
> if ($str2 =~ /$reg2/) {
>     print <<""
> Two
>   title: $2
>   link:  $1
>   descr: $3
>
> }
> -- 
> Hope this helps,
> Steven
>

Yes it does. I've used lookahead to, for example, extract only links to the
/bin/ directory:

$string =~ m|<a href="(?=/bin/)([^"]+)">([^<]+)<|;

but I never thought to capture data inside the lookahead.

Thank you,

Todd W.




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

Date: Fri, 11 Feb 2005 00:12:54 +0000 (UTC)
From: Gerald Jones <gj@freeshell.org>
Subject: track how many moves to sort an array?
Message-Id: <cugta6$5ec$1@chessie.cirr.com>


Lets say I have an array with 10 elements, such as:

@a = ( "ian", "albert", "chris", "ed", "bertram", "david", "john", "fred",
"george", "harry");

I am interested in determining how many moves it would take to  sort this
alphabetically.  Now, I could re-implement Perl's built in sort mechanism and
have an incremented value in there somewhere,  but first I'd like to know if
there was any way to do this with the built-in sort. The perldoc says this:

[snip]

If SUBNAME or BLOCK is omitted, sorts in standard string comparison order. If
SUBNAME is specified, it gives the name of a subroutine that returns an integer
less than, equal to, or greater than 0, depending on how the elements of the
list are to be ordered. (The <=> and cmp operators are extremely useful in such
routines.)

[/snip]

Huh?  And how can I extrapolate these number is into number of moves to get to:


@a = ( albert", "bertram", "chris", "david", "ed", "fred",
"george", "harry", "ian", "john" );


 .... anyways? So far, I got:

$ perl -e 'while (<>) { push( @a, $_) } @b = sort { print $a <=> $b, "\n" } @a; foreach $b (@b) { print "$b" }'
zed
ded
head
bread
aded
0
0
0
0
0
aded
bread
head
ded
zed
$


Which is wrong, but I have no idea how to interpret this let alone determine
how close I am to being correct.  Any insight any one has would be appreciated!

Thanks, Gerald


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

Date: Thu, 10 Feb 2005 18:05:00 -0700
From: Scott Bryce <sbryce@scottbryce.com>
Subject: Re: track how many moves to sort an array?
Message-Id: <RI2dne5hAaMhmZHfRVn-vA@comcast.com>

Gerald Jones wrote:

> Lets say I have an array with 10 elements, such as:
> 
> @a = ( "ian", "albert", "chris", "ed", "bertram", "david", "john", "fred",
> "george", "harry");
> 
> I am interested in determining how many moves it would take to  sort this
> alphabetically.

Though I'm not sure what purpose this serves, this does what you are 
describing.


use strict;
use warnings;

my @list = qw( ian
                albert
                chris
                ed
                bertram
                david
                john
                fred
                george
                harry);

my $count = 0;					
					
@list = sort {$count ++; $a cmp $b} @list;

print join ', ', @list;
print "\nThe sort required $count steps.\n";


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

Date: Fri, 11 Feb 2005 01:12:13 GMT
From: "Todd W" <toddrw69@excite.com>
Subject: Re: track how many moves to sort an array?
Message-Id: <NDTOd.5626$hU7.3136@newssvr33.news.prodigy.com>


"Gerald Jones" <gj@freeshell.org> wrote in message
news:cugta6$5ec$1@chessie.cirr.com...
>
> Lets say I have an array with 10 elements, such as:
>
> @a = ( "ian", "albert", "chris", "ed", "bertram", "david", "john", "fred",
> "george", "harry");
>
> I am interested in determining how many moves it would take to  sort this
> alphabetically.  Now, I could re-implement Perl's built in sort mechanism
and
> have an incremented value in there somewhere,  but first I'd like to know
if
> there was any way to do this with the built-in sort. The perldoc says
this:
>
> [snip]
>
> If SUBNAME or BLOCK is omitted, sorts in standard string comparison order.
If
> SUBNAME is specified, it gives the name of a subroutine that returns an
integer
> less than, equal to, or greater than 0, depending on how the elements of
the
> list are to be ordered. (The <=> and cmp operators are extremely useful in
such
> routines.)
>
> [/snip]
>
> Huh?  And how can I extrapolate these number is into number of moves to
get to:
>
>
> @a = ( albert", "bertram", "chris", "david", "ed", "fred",
> "george", "harry", "ian", "john" );
>
>
> .... anyways? So far, I got:
>
> $ perl -e 'while (<>) { push( @a, $_) } @b = sort { print $a <=> $b,
"\n" } @a; foreach $b (@b) { print "$b" }'

<snip />

because you are comparing strings you need to use "cmp" instead of the
numeric comparison operator "<=>"

if you wouldve added a -w flag to your oneliner you'd of found that out.

Heres what I came up with:

[trwww@waveright trwww]$ perl
use warnings;
use strict;

my @orig = qw(ian albert chris ed bertram david john fred george harry);
my $count;
my @sort = sort( { $count++; $a cmp $b } @orig );
print "$count iterations:\n";
print map( "$_\n", @sort );
Ctrl-D
24 iterations:
albert
bertram
chris
david
ed
fred
george
harry
ian
john

Todd W.




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

Date: Fri, 11 Feb 2005 01:30:48 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: track how many moves to sort an array?
Message-Id: <cVTOd.19057$uc.273@trnddc08>

Scott Bryce wrote:
> Gerald Jones wrote:
>
>> Lets say I have an array with 10 elements, such as:
>>
>> @a = ( "ian", "albert", "chris", "ed", "bertram", "david", "john",
>> "fred", "george", "harry");
>>
>> I am interested in determining how many moves it would take to  sort
>> this alphabetically.
>
> @list = sort {$count ++; $a cmp $b} @list;

Not quite. You are counting how often two elements are compared.
The OP was asking for how often elements are "moved" (by whatever definition 
of "move").

jue 




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

Date: Fri, 11 Feb 2005 01:31:51 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: track how many moves to sort an array?
Message-Id: <bWTOd.19059$uc.390@trnddc08>

Gerald Jones wrote:
> Lets say I have an array with 10 elements, such as:
>
> @a = ( "ian", "albert", "chris", "ed", "bertram", "david", "john",
> "fred", "george", "harry");
>
> I am interested in determining how many moves it would take to  sort
> this alphabetically.

This very much depends upon which sort algorithm you are using and how you 
define a "move".

jue




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

Date: Thu, 10 Feb 2005 19:11:57 -0700
From: Scott Bryce <sbryce@scottbryce.com>
Subject: Re: track how many moves to sort an array?
Message-Id: <UY-dneNtNqHziZHfRVn-hg@comcast.com>

Jürgen Exner wrote:

> Not quite. You are counting how often two elements are compared.

# Perhaps this is what the OP wanted?
@list = sort {$count ++ if $a gt $b; $a cmp $b} @list;

> The OP was asking for how often elements are "moved" (by whatever definition 
> of "move").

As you point out, it depends on what the OP means by "move."


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

Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>


Administrivia:

#The Perl-Users Digest is a retransmission of the USENET newsgroup
#comp.lang.perl.misc.  For subscription or unsubscription requests, send
#the single line:
#
#	subscribe perl-users
#or:
#	unsubscribe perl-users
#
#to almanac@ruby.oce.orst.edu.  

NOTE: due to the current flood of worm email banging on ruby, the smtp
server on ruby has been shut off until further notice. 

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

#To request back copies (available for a week or so), send your request
#to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
#where x is the volume number and y is the issue number.

#For other requests pertaining to the digest, send mail to
#perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
#sending perl questions to the -request address, I don't have time to
#answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V10 Issue 7769
***************************************


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