[15711] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 3124 Volume: 9

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Mon May 22 14:15:48 2000

Date: Mon, 22 May 2000 11:15:26 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <959019326-v9-i3124@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Mon, 22 May 2000     Volume: 9 Number: 3124

Today's topics:
        Reposting, can't retrieve my hash from an oher script <vincent@luckysurf.com>
        run external command and re-direct output to a variable <kam_nospam@bgmm.com>
    Re: run external command and re-direct output to a vari <andersen+@rchland.ibm.com>
        SDBM_File - %HASH not returning all records ? <miguel_thomasNOmiSPAM@hotmail.com.invalid>
        simple array question <reevesg@cableinet.co.ukx>
    Re: simple array question <blah@nospam.com>
    Re: simple array question <jboesNOjbSPAM@qtm.net.invalid>
    Re: simple array question <andersen+@rchland.ibm.com>
    Re: simple array question <godzilla@stomp.stomp.tokyo>
    Re: simple array question <sariq@texas.net>
    Re: simple array question <sariq@texas.net>
        Simple Module Creation <skpurcell@hotmail.com>
    Re: Simple Module Creation <jboesNOjbSPAM@qtm.net.invalid>
    Re: Simple Module Creation nobull@mail.com
    Re: Sorting a hash <bmb@dataserv.libs.uga.edu>
    Re: Sorting a hash <register_ms@hotmail.com>
    Re: Sorting a hash (Elliot Finley)
    Re: sorting a list of mixed numbers and text as in perl (Gwyn Judd)
    Re: sorting a list of mixed numbers and text as in perl <andrew.mcguire@walgreens.com>
    Re: sorting a list of mixed numbers and text as in perl <lr@hpl.hp.com>
    Re: Tanspose rows to columns <mjcarman@home.com>
    Re: Tanspose rows to columns <iltzu@sci.invalid>
    Re: Untaint URL character class (Bart Lateur)
    Re: Untaint URL character class <godzilla@stomp.stomp.tokyo>
    Re: updated : Re: regexes *sigh* damn I hate these thin <godzilla@stomp.stomp.tokyo>
    Re: Using DBM for simple database? (Bart Lateur)
    Re: Using several remote shell commands in print FILEHA <rootbeer@redcat.com>
    Re: valid email address (Abigail)
    Re: valid email address (Abigail)
    Re: What's this line which Perl added to AUTOEXEC.BAT? <waldo700NOwaSPAM@aol.com.invalid>
    Re: Windows/Linux Incompatibility nobull@mail.com
        Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)

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

Date: Mon, 22 May 2000 17:05:49 GMT
From: "Vincent" <vincent@luckysurf.com>
Subject: Reposting, can't retrieve my hash from an oher script
Message-Id: <NNdW4.682$Qh1.2683009@nnrp2.proxad.net>

I already posted this problem but didn't get any answer. So if anyone knows
something about it I would be very thankfull about him.

This is the problem.
I have two scripts.
    *The first one : 'startup.pl' is called when I restart Apache. In this
script I put every html pages in a hash.
At this moment, My hash is full, I can print it, and there is no preblem.

    *The second one : 'play' is called anytime I am looking a page which
call
this script. But there I can't retrieve the page anymore. My Hash if empty.

So, in brief, my hash do exist because I can print it when I restart Apache,
but  5 seconds after when an other script try to retrieve the information
from this hash it says that this hash is empty.



This is the code I wrote :
########
#in startup.pl
########
use vars qw(%file_cache);

sub load_file
{ 
    my($fn) = @_; 
    local(*IN); 
    my($file); 
    if (open(IN, $fn)) { 
        read(IN, $file, -s IN); 
        close(IN); 
    } 
    else { 
        my ($dir, $name) = split( /\//, $fn, 2 ); 
        $fn="NewSite/$name"; 
        if (open(IN, $fn)) { 
        read(IN, $file, -s IN); 
        close(IN); 
    } 
} 
$file; 
} 

sub processing_directory($) #to parse directory 
{ 
my $folder = $_[0]; 
my $fName = $folder; 
my $file; 
local (*FOLD); 

    $fName =~ s/.*\///; 
    opendir( FOLD, $folder) or die "Can't open $folder: ! 
    $\n"; 

    while(defined($file = readdir(FOLD))) { 
        next if $file =~ /^\.\.?$/; 
        if(!-d "$file") { 
            $file_cache{"$fName/$file"} = load_file ("$folder/$file") if $file =~ /.*\.html$/; 
            print "$fName/$file\n"; 
        } 
        else { 
            processing_directory(sprintf("%s/%s", 
            $folder, $file)); 
        } 
    } 
    closedir(FOLD); 
} 
######## 
#in play 
######## 
sub load_file_hinted_core($$) 
{ 
my($name, $valref) = @_; 
my $s; 

    unless ($main::debugMode) { 
        $s = $main::file_cache{"$valref->{site}/$name"}; 
        $
req->warn ("Page $valref->{site}/$name unknown") unless $s;
    }
    unless ($s)

        $s = load_file("$valref->{site}/$name");
    }

there, everytime I got  "Page  *****  unknown"




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

Date: Mon, 22 May 2000 15:51:25 GMT
From: kam <kam_nospam@bgmm.com>
Subject: run external command and re-direct output to a variable?
Message-Id: <3929557C.153520C2@bgmm.com>

This is code snip that we're using.  We're able to successfully
re-direct the information to the
file define by $displaydatafile, which is a file.

    my @progArg = ("$executable", "$index", "$license", "$qArg",
"$pipeout", "$displaydatafile");
    system("@progArg") == 0 || die "system @progArg failed: $?";

We're read some of the FAQ's but haven't found any good hints.  Is there
a way of capturing
this to a Variable instead of outputting to a file and then having to
input the information?

Any thoughts would be appreciated.  Our platform is Windows NT 4.0.

Regards,




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

Date: Mon, 22 May 2000 11:41:28 -0500
From: "Paul R. Andersen" <andersen+@rchland.ibm.com>
Subject: Re: run external command and re-direct output to a variable?
Message-Id: <39296338.76D7F4CB@rchland.ibm.com>

kam wrote:
> 
> This is code snip that we're using.  We're able to successfully
> re-direct the information to the
> file define by $displaydatafile, which is a file.
> 
>     my @progArg = ("$executable", "$index", "$license", "$qArg",
> "$pipeout", "$displaydatafile");
>     system("@progArg") == 0 || die "system @progArg failed: $?";
> 
> We're read some of the FAQ's but haven't found any good hints.  Is there
> a way of capturing
> this to a Variable instead of outputting to a file and then having to
> input the information?
> 
> Any thoughts would be appreciated.  Our platform is Windows NT 4.0.
> 
> Regards,

If you execute things with backticks you can capture output

$CmdRet = `$executable $arg1`;

will put the output of the executable in $CmdRet and you can display it
or write to a file or whatever. 
-- 
Paul Andersen
-- I can please only ONE person per day.
-- Today is NOT your day.
-- Tomorrow isn't looking good either.


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

Date: Mon, 22 May 2000 09:20:35 -0700
From: Miggy <miguel_thomasNOmiSPAM@hotmail.com.invalid>
Subject: SDBM_File - %HASH not returning all records ?
Message-Id: <08557e51.1df45261@usw-ex0105-034.remarq.com>

I'm working with ActivePerl 613 on a Windows 98 SE box through
MS-DOS prompt.

I'm having some trouble with the SDBM_File functions in my PERL
database routines.

I'm creating the following records, all types are different data
lengths, in this order :-

1 record type "A" using key "KEYADMIdave"
1 record type "B" using key "KEYDEALfred"
1 record type "C" using key "KEYREPRjoe"

1 record type "D" using
key "KEYSESSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
1 record type "D" using
key "KEYSESSdddddddddddddddddddddddddddddddddddddddd"
1 record type "D" using
key "KEYSESSrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"

Up to here, no problems. Then I created the following records,
as I wanted to test splitting results into blocks of 20 on
different HTML pages :-

40 records type "A" using keys "KEYADMIadmin1", "KEYADMIadmin2"
up to "KEYADMIadmin40"

So I now have...

Record type "A" - 41no.
Record type "B" - 1no.
Record type "C" - 1no.
Record type "D" - 3no.
TOTAL	46no.

Now, when I ran my script, I noticed that some of the records
type "A" were missing.

If I access the database using each invidual key "KEYADMIadmin1"
or "KEYADMIadmin2" etc, the data is correct for each record -
the records DO exist. But if I try any of the following code
snippets, not all the records are being returned ?

@foo = map {/^KEYADMI(.+)\Z/} keys(%bar);

Here @foo ends up with only 37, or sometimes 33 records, when it
should contain 41 !

while (($foo, $foo2) = each(%bar)) {
	print $foo;
}

Here, only 38 or 42 records are printed, where it should be 46 !

foreach $foo (keys %bar) {
	print $foo;
}

Here, again only 38 or 42 records, should be 46 !

So what am I missing - are there any known problems with
SDBM_File - are my key names too big - can UPPER and lower case,
alpha and numeric mixes be used and identified uniquely by
SDBM_File, or are they all interpreted as lower case i.e. are my
keys all unique - what is the problem ?

When I look at the raw database .PAG file, it "seems" to have
all the data - this is confirmed by the fact that I can access
the data by individual key - I just can't get a list of ALL the
keys !

For future info, what are the maximum allowed lengths of keys
and records for this SDBM_File, and could anybody give me some
pointers to Web pages, references etc. for SDBM_File databases ?

If anyone suggests that I use Berkeley's DB_File instead -
please send me a precompiled port for Windows 98 ! Ultimate
irony there, they will give me the source code free, (but my CD
with VC++ on it is broken, so I can't reinstall or do any
compilation work after my last hard disk wipe), but they won't
give me a pre-compiled EXE unless I become a "prepaid" member -
and I can't find one on the net either !

I'd prefer to stick with SDBM_File if possible, as I understand
it's on every UNIX box bundled with PERL anyway - my scripts
would be more portable that way.

Please, I only started PERL last week, I'm really a Windows type
person, and this is VERY frustrating (especially when doing it
on Windows, so I'm not sure if it will all work on a UNIX box
anyway) !

Ideas, as soon as possible please !



* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!



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

Date: Mon, 22 May 2000 16:18:10 GMT
From: "red [2]" <reevesg@cableinet.co.ukx>
Subject: simple array question
Message-Id: <65dW4.473$sE.39245@news3.cableinet.net>

can i get the number of values in an array without going through a foreach
loop?
eg if i opened a file and
@myarray=<FILELINES>;
how do i get the amount of "lines" in @myarray?

--

Graham "red" Reeves

uk's Q3 news & features - - www.quadmonkey.co.uk
domains for sale - - http://www.quadmonkey.co.uk/files/forsale.html
the stupid - - http://www.thestupid.com
member of clan [2] - - http://www.clan2.com





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

Date: Mon, 22 May 2000 18:32:17 +0200
From: Marco Natoni <blah@nospam.com>
Subject: Re: simple array question
Message-Id: <39296111.19563@nospam.com>

"red [2]",

"red [2]" wrote:
> can i get the number of values in an array without going through 
> a foreach loop? eg if i opened a file and @myarray=<FILELINES>; how 
> do i get the amount of "lines" in @myarray?

  Basically:

<code>
	$arraysize=@myarray;	# "when an array is evaluated as a 
				# scalar, the number of elements in 
				# the array is returned"
	$arraylast=$#myarray;	# "this special form of an array 
				# value returns the index of the 
				# last member of the list (one less 
				# than the number of elements)"
</code>


	Best regards,
		Marco


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

Date: Mon, 22 May 2000 09:43:16 -0700
From: Mur <jboesNOjbSPAM@qtm.net.invalid>
Subject: Re: simple array question
Message-Id: <10053164.3a2459c9@usw-ex0101-006.remarq.com>

In article <65dW4.473$sE.39245@news3.cableinet.net>, "red [2]"
<reevesg@cableinet.co.ukx> wrote:

>how do i get the amount of "lines" in @myarray?

$number_of_lines = @myarray;

How could that be any easier? 8-)



Jeff Boes//ICQ=3394914//Yahoo!=jeffboes//AOL IM=jboes
  //home=jboes@qtm.net//professional=mur@consultant.com

* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!



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

Date: Mon, 22 May 2000 11:43:35 -0500
From: "Paul R. Andersen" <andersen+@rchland.ibm.com>
Subject: Re: simple array question
Message-Id: <392963B7.422AC4B4@rchland.ibm.com>

"red [2]" wrote:
> 
> can i get the number of values in an array without going through a foreach
> loop?
> eg if i opened a file and
> @myarray=<FILELINES>;
> how do i get the amount of "lines" in @myarray?
> 
> --
> 
> Graham "red" Reeves
> 
> uk's Q3 news & features - - www.quadmonkey.co.uk
> domains for sale - - http://www.quadmonkey.co.uk/files/forsale.html
> the stupid - - http://www.thestupid.com
> member of clan [2] - - http://www.clan2.com

$#myarray will contain the number of the next array element to be
assigned to so (remembering that arrays start at zero) if you have 10
items in the array $#myarray will return a 10.

-- 
Paul Andersen
-- I can please only ONE person per day.
-- Today is NOT your day.
-- Tomorrow isn't looking good either.


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

Date: Mon, 22 May 2000 10:03:44 -0700
From: "Godzilla!" <godzilla@stomp.stomp.tokyo>
Subject: Re: simple array question
Message-Id: <39296870.A675303A@stomp.stomp.tokyo>

"red [2]" wrote:
 
> can i get the number of values in an array 
> without going through a foreach loop?
> eg if i opened a file and
> @myarray=<FILELINES>;
> how do i get the amount of "lines" in @myarray?


This format, one of a few, might help you
quickly and easily:

$#myarray+1


This is a simple example of how
this format works:


Test Script:
________________

#!/usr/local/bin/perl

print "Content-Type: text/plain\n\n";

@Test_Array = ("one", "two", "three");

$count = ($#Test_Array+1);

print "Number of elements is $count";

exit;



Printed Results:
________________

Number of elements is 3


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

Date: Mon, 22 May 2000 12:48:39 -0500
From: Tom Briles <sariq@texas.net>
Subject: Re: simple array question
Message-Id: <392972F7.4891E9AD@texas.net>

Marco Natoni wrote:
> 
>         $arraylast=$#myarray;   # "this special form of an array
>                                 # value returns the index of the
>                                 # last member of the list (one less
>                                 # than the number of elements)"

Not exactly.

perldoc perldata

- Tom


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

Date: Mon, 22 May 2000 12:50:10 -0500
From: Tom Briles <sariq@texas.net>
Subject: Re: simple array question
Message-Id: <39297352.F84FAC20@texas.net>

"Paul R. Andersen" wrote:
> 
> $#myarray will contain the number of the next array element to be
> assigned to so (remembering that arrays start at zero) if you have 10
> items in the array $#myarray will return a 10.

Where in the world did you get that idea?

perldoc perldata

- Tom


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

Date: Mon, 22 May 2000 10:48:36 -0500
From: "spurcell" <skpurcell@hotmail.com>
Subject: Simple Module Creation
Message-Id: <392956da$0$10601@wodc7nh1.news.uu.net>

Hello,
I work on an API of a properiety software package, and am constantly hitting
their DB with queries.

Anyway, I was wondering if I could produce a module to do such a thing.? It
would be very simple, but I get tired of typing constantly the same thing.

Here is a basic syntax to a query.
my $qstring = "\' \'\$FILENAME";
my $fieldval = "FILENAME\nID\nOTHER";
my $dbpath = "somelongunixstylepath";
&GetQuery($qstring,$fieldval,$dbpth);

And in the GetQuery, it does some other socket stuff.

Anyway, do I have to know Objects to write a simple module for a routine
like this? And if it is do-able, does anyone have a sample of a very simple
module like this that I could learn from? Or would someone be willing to
help me with this on-line?

Thanks
Scott




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

Date: Mon, 22 May 2000 09:35:02 -0700
From: Mur <jboesNOjbSPAM@qtm.net.invalid>
Subject: Re: Simple Module Creation
Message-Id: <207d7ac0.37ff9156@usw-ex0101-006.remarq.com>

This page may be of help:

http://world.std.com/~swmcd/steven/perl/module_anatomy.html


>Here is a basic syntax to a query.
>my $qstring = "\' \'\$FILENAME";
>my $fieldval = "FILENAME\nID\nOTHER";
>my $dbpath = "somelongunixstylepath";
>&GetQuery($qstring,$fieldval,$dbpth);

But why do you need a module for this? Is GetQuery returning a
simple value, or an object? Seems to me that all you need is...

my $qstring = "\' \'\$FILENAME";
my $fieldval = "FILENAME\nID\nOTHER";
my $dbpath = "somelongunixstylepath";
&MyGetQuery($qstring,$fieldval,$dbpth);

sub MyGetQuery(@) {
  &GetQuery(@_);
}

or something equally dull.


Jeff Boes//ICQ=3394914//Yahoo!=jeffboes//AOL IM=jboes
  //home=jboes@qtm.net//professional=mur@consultant.com

* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!



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

Date: 22 May 2000 17:46:16 +0100
From: nobull@mail.com
Subject: Re: Simple Module Creation
Message-Id: <u94s7qr0rr.fsf@wcl-l.bham.ac.uk>

"spurcell" <skpurcell@hotmail.com> writes:

> I work on an API of a properiety software package, and am constantly hitting
> their DB with queries.
> 
> Anyway, I was wondering if I could produce a module to do such a thing.? It
> would be very simple, but I get tired of typing constantly the same thing.
>
> Here is a basic syntax to a query.
> my $qstring = "\' \'\$FILENAME";
> my $fieldval = "FILENAME\nID\nOTHER";
> my $dbpath = "somelongunixstylepath";
> &GetQuery($qstring,$fieldval,$dbpth);
> 
> And in the GetQuery, it does some other socket stuff.
> 
> Anyway, do I have to know Objects to write a simple module for a routine
> like this?

No.

> And if it is do-able, does anyone have a sample of a very simple
> module like this that I could learn from? Or would someone be willing to
> help me with this on-line?

use strict;

package MyModule;
use base qw(Exporter);
use vars qw(@EXPORT);
@EXPORT = qw( myfunc );

sub myfunc {
  # whatever
}

-- 
     \\   ( )
  .  _\\__[oo
 .__/  \\ /\@
 .  l___\\
  # ll  l\\
 ###LL  LL\\


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

Date: Mon, 22 May 2000 11:10:21 -0400
From: Brad Baxter <bmb@dataserv.libs.uga.edu>
Subject: Re: Sorting a hash
Message-Id: <Pine.GSO.4.21.0005221108380.1496-100000@dataserv.libs.uga.edu>

On Mon, 22 May 2000, Gert wrote:

> # Let's sort the keys now. Highest number first. So I thought....
> @keys = sort {
>                     $sites{$b} cmp $sites{$a}
>             } keys %sites;

Did you say "number"?

s/cmp/<=>/;

-- 
Brad



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

Date: Mon, 22 May 2000 17:18:59 +0200
From: Gert <register_ms@hotmail.com>
Subject: Re: Sorting a hash
Message-Id: <8ujiiscn38eunkrdpjeq750aak4ottl94d@4ax.com>

On Mon, 22 May 2000 16:17:20 +0200, Gert <register_ms@hotmail.com> had
the nerve to write: 

Thank you!

Gert


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

Date: Mon, 22 May 2000 15:28:57 GMT
From: efinley@efinley.com (Elliot Finley)
Subject: Re: Sorting a hash
Message-Id: <3929520b.129823866@news.firstworld.net>

On Mon, 22 May 2000 16:17:20 +0200, Gert <register_ms@hotmail.com>
wrote:

>Hello all,
>
>I am currently working on a linkspage with a redirect script to see
>which links are used and which are not.
>
>Another script is processing the logfiles.
>The pagecounts are stuffed in a hash, and the hash is sorted by the
>script found in the perlfaq (4 I think...)
>Everything went very well until after a few minutes a page hit the 10
>visits. Now the sorting looks like this:
>
>6, 5, 4, 3, 2, 10, 1, 1, 1
>
>How do I sort my hash to move the largest number up front?
>
>The script is printed below.
>
>Many thanks in advance!
>
>Gert.
>____
>#c:\perl\bin\perl.exe
>
>use strict;
>use vars qw($line $logfile);
>
>my $logdir = "d:\\www\\linklog";
># I still hate to use the double backslash, but that's the sacrifices
># I make for coding on a windows box....
>
>my %sites;
>my @logfiles = glob("$logdir\\*.log");
>
># This pulls all the logfiles out of the dir and stuffs them into an
>array.
>
>foreach $logfile (@logfiles) {
>	open(EDIT, $logfile) || die "Cannot open $logfile";
>	$logfile =~ s/d:\\www\\linklog\\//;
>	$logfile =~ s/.log//;
>	$logfile =~ s/_/\//g;
>	my @lines = <EDIT>;
>	close(EDIT);
>	foreach $line (@lines) {
>		my ($Time, $ReHo, $Date) = split(/\|/, $line);
>		$sites{$logfile}++;
>	}
>}
>
>print "Content-type:text/html\n\n";
>print "<table width=100%><tr><td width=50%></td><td
>width=50%></td></tr>";
># (Necessary for the browser to understand this stuff)
>
># Let's sort the keys now. Highest number first. So I thought....
>@keys = sort {
>                    $sites{$b} cmp $sites{$a}

change 'cmp' to '<=>' to compare numerically.

>            } keys %sites;
>
>
>
># Now iterate through the keys and print the whole bunch
>foreach $key (@keys) {
>	print "<tr><td>$key:</td><td> <img src='/axs/red.gif' height=5
>width=$sites{$key}0> ($sites{$key} visitors)\n</td></tr>";
>}
>
>print "</table>";
># The end....

-- 
Elliot (efinley@efinley.com) Weird Science!


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

Date: Mon, 22 May 2000 15:06:34 GMT
From: tjla@guvfybir.qlaqaf.bet (Gwyn Judd)
Subject: Re: sorting a list of mixed numbers and text as in perldoc
Message-Id: <slrn8il7nt.5tv.tjla@thislove.dyndns.org>

I was shocked! How could The WebDragon <nospam@devnull.com>
say such a terrible thing:
>In article <Pine.LNX.4.20.0005212035420.18426-100000@hawk.ce.mediaone.net>, 
>"Andrew N. McGuire " <anmcguire@ce.mediaone.net> wrote:
> | Reverse $a and $b in the quoted line above, like so:
> | 
> | sort { $a->[1] <=> $b->[1]
>
>Like this? :
>
>#!/usr/bin/perl -w
>
>use POSIX qw(INT_MAX);
>
>@old = qw(hi low 1 2 3 yo what's up dawg?);
>
># set this to INT_MAX to sort text before numbers or set to 0 to sort
># numbers before text
>$text_first = INT_MAX;
>
>@new = map { $_->[0] }
>  sort { $a->[1] <=> $b->[1]
>                 ||
>         $a->[2] cmp $b->[2]
>  } map { [$_, m/(\d+)/ ? $1 : $text_first, uc($_)] } @old;
>
>print join " ", @old;
>print "\n";
>print join " ", @new;
>
>no, I tried that .. this results in 
>====
>    1 2 3 dawg? hi low up what's yo
>====
>when what I wanted was this: 
>====
>    dawg? hi low up what's yo 1 2 3
>====

ewww you found a bug :). looks like the "text_first" thingy only works
correctly when we try to sort the numbers in reverse order, otherwise we
have to reverse the sense of it. It's not a very well named variable
either. oh well I am only an egg.

looks like if you want to sort the text characters first you need to
take into account whether or not you are sorting the numbers/text in the
right order as well. sounds weird to me. here's what I am thinking, feel
free to step in and correct me: 

firstly a non-numerical ie. text "word" is given
a "numerical value" of INT_MAX, assuming you want the text to sort
*last* and you want the words and text to sort in normal (ie. ascending)
order (for whatever that means for words or text). This means that any
text will have a value greater than any number so it sorts after any
number by the first comparison ($a->[1] <=> $b->[1]). That is what we
get up there so it's okay.

okay so now assuming you want to sort numbers in descending order then
this is where everything is stuffed up. what happens now is that the
text that you still want to sort after the numbers (so it has the
"numerical value" of INT_MAX) will not sort before the numbers! This is
because we have turned the first compare around (now $b->[1] <=>
$a->[1]).

This will fortunately only happen when we switch the first
comparison around, since whenever we do the second comparison we will
always be comparing two text words *as text* (ie. we never compare text
vs. number in the second comparison).

So to fix this what we have to do is determine beforehand not only
whether we want to sort "text first" or not, but also what order we want
to sort the numbers in (and I suppose the text as well for
completeness). *if* we want to sort the numbers in descending order then
we set that funny (badly named) text_first variable to -INT_MAX (not 0
as I had before, another bug). hence the sign of the "numerical value"
of any text is given by this pathetic chart:

tf/na | 0 | 1
---------------
  0   | - | +
---------------
  1   | + | -

Then all we have to do is rearrange the order of the compares depending
on which order we are sorting the numbers or text. After all that the
finished code. I hope it works now.

#!/usr/bin/perl -w

use POSIX qw(INT_MAX);

@old = qw(hi low 1 2 3 yo what's up dawg?);

$numbers_ascending = 1;
$text_ascending = 1;

$text_first = 1;

$text_val = [[-1,1],[1,-1]]->[$numbers_ascending][$text_first] *
INT_MAX;

@new = map { $_->[0] }
  sort { ($a->[1] <=> $b->[1]) * ($numbers_ascending ? 1 : -1)
                 ||
         ($a->[2] cmp $b->[2]) * ($text_ascending ? 1 : -1)
  } map { [$_, m/(\d+)/ ? $1 : $text_val, uc($_)] } @old;

print join " ", @old;
print "\n";
print join " ", @new;

my newsreader may have wrapped stuff but it works *here* anyway :).

-- 
Gwyn Judd (tjla@guvfybir.qlaqaf.bet)
My return address is rot13'ed
I have yet to see any problem, however complicated, which, when
you looked at it in the right way, did not become still more complicated.
		-- Poul Anderson


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

Date: Mon, 22 May 2000 11:52:32 -0500
From: "Andrew N. McGuire" <andrew.mcguire@walgreens.com>
Subject: Re: sorting a list of mixed numbers and text as in perldoc
Message-Id: <Pine.GSO.4.21.0005221149250.1017-100000@sputnik.corp.walgreens.com>

On 22 May 2000, The WebDragon wrote:

+ In article <Pine.LNX.4.20.0005212035420.18426-100000@hawk.ce.mediaone.net>, 
+ "Andrew N. McGuire " <anmcguire@ce.mediaone.net> wrote:
+ 
+  | On 22 May 2000, The WebDragon wrote:
+  | 
+  | + In article <slrn8idf1j.tkm.tjla@thislove.dyndns.org>, 
+  | tjla@guvfybir.qlaqaf.bet 
+  | + (Gwyn Judd) wrote:
+  | 
+  | [ snip ]
+  | 
+  | +  |   sort { $b->[1] <=> $a->[1]
+  | 
+  | [ snip ]
+  | 
+  | + what if you wanted the output to be:
+  | + 
+  | + ====
+  | + dawg? hi low up what's yo 1 2 3
+  | + ====
+  | + 
+  | + how would you change that?
+  | 
+  | Reverse $a and $b in the quoted line above, like so:
+  | 
+  | sort { $a->[1] <=> $b->[1]
+ 
+ Like this? :

[ snip code ]

+ no, I tried that .. this results in 
+ ====
+     1 2 3 dawg? hi low up what's yo
+ ====
+ when what I wanted was this: 
+ ====
+     dawg? hi low up what's yo 1 2 3
+ ====

Well, this does what you want... But is probably not the best way.

#!/usr/bin/perl -w
use strict;

use POSIX qw[INT_MAX];

my @unsorted = qw[hi low 1 2 3 yo what's up dawg?];
my @sorted;
my $text_first = INT_MAX;

{

local $^W = 0;
@sorted = map { $_->[0] }
    sort { $a->[0] <=> $b->[0]
                   ||
           $a->[0] cmp $b->[0]
} map { [$_, m/(\d+)/ ? $1 : $text_first, uc($_)] } @unsorted;

}

print join " ", @unsorted;

print "\n";
print join " ", @sorted;

I just put the numeric comparison first, but that creates
warnings. hence the resetting of $^W.  I think this is kinda
ugly though, there must be a better way.

Best Wishes,

anm
-- 
/*-------------------------------------------------------.
| Andrew N. McGuire                                      |
| andrew.mcguire@walgreens.com                           |
`-------------------------------------------------------*/



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

Date: Mon, 22 May 2000 10:44:04 -0700
From: Larry Rosler <lr@hpl.hp.com>
Subject: Re: sorting a list of mixed numbers and text as in perldoc
Message-Id: <MPG.139311bb8e56dbbd98aaac@nntp.hpl.hp.com>

In article <Pine.GSO.4.21.0005221149250.1017-
100000@sputnik.corp.walgreens.com> on Mon, 22 May 2000 11:52:32 -0500, 
Andrew N. McGuire <andrew.mcguire@walgreens.com> says...

 ...


> local $^W = 0;
> @sorted = map { $_->[0] }
>     sort { $a->[0] <=> $b->[0]
>                    ||
>            $a->[0] cmp $b->[0]
> } map { [$_, m/(\d+)/ ? $1 : $text_first, uc($_)] } @unsorted;

 ...

> I just put the numeric comparison first, but that creates
> warnings. hence the resetting of $^W.  I think this is kinda
> ugly though, there must be a better way.

Well, of course there is.  The Guttman-Rosler Transform makes this 
problem almost trivial, and faster than any of the other solutions also.

The trick is to make a lexicographically sortable key out of the 
numbers, prefixed with a character that forces them all to sort before 
the alphabetical entries.  This would happen automatically without a 
prefix for all but the hugest numbers, but the prefix makes it a 
certainty, at the negligible cost of one more character to sort on.


#!/usr/local/bin/perl -w
use strict;

my @unsorted = qw[hi low 1 2 3 yo what's up dawg?];

my @sorted = map substr($_, 1 + rindex $_, "\0") => sort
    map { (/(\d+)/ ? 0 . pack N => $1 : 1 . uc) . "\0$_" } @unsorted;

print "@unsorted\n@sorted\n";


-- 
(Just Another Larry) Rosler
Hewlett-Packard Laboratories
http://www.hpl.hp.com/personal/Larry_Rosler/
lr@hpl.hp.com


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

Date: Mon, 22 May 2000 09:22:00 -0500
From: Michael Carman <mjcarman@home.com>
Subject: Re: Tanspose rows to columns
Message-Id: <39294288.ED23D077@home.com>

Xah wrote:
> 
> > It builds a string for eval() every time it's called. [...]
> > Was that the only way you could find to do it?
> 
> Yes, and if you could show me it without eval [...]

If it's truly needed then that's fine -- it's just an efficiency hit.
Getting around it is an interesting challenge, and there's probably a a
way, though it might require some comprimises in the level of arbitrary
complexity you're trying to support. I don't mean not supporting some
functionality; I'm thinking more along the lines of the DFT vs. the FFT;
have more efficient handling of special/common cases, and save the big
gun of eval() for the really hairy stuff if there's no other way.

At any rate, I don't have the time to play with it at present. Perhaps
someone else will take you up on your offer.

> The perl folks of beady eyes and unix weenies of lose mouths,

I've chided you about this attitude before. Can't you make an argument
without going out of your way to insult people?

> have this peculiar propensity toward trifles. You see them everywhere
> getting extremely upset about newsgroup post formats, [...]

It's called nettiquette. Manners are important on Usenet, as they are in
life, though this seems to be lost on you. (See previous comment.)
Sharing the rules with the uninitiated is a Good Thing. Postings with
mangled line-wrapping, WaReZ style, or other oddities are hard to read
and distract from the content. Personal modes of expression are fine,
but this forum is intended to be a community, not just a bunch of
individuals. That's what the conventions are for. 
 
> In subjects they take an interest in, they are oblivious to what is
> really important. They are excited by speedier implementation, but
> little interest in better algorithm complexity.

I don't see why you feel that increasing complexity is intrinsically a
good thing. Do you get in your car and drive if you're only going next
door?

> > BTW, Xah, if you despise Perl so much [...] why program in it?
> 
> There are things in this world that we do not get to choose,

Yes, but this isn't one of them.

-mjc


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

Date: 22 May 2000 15:33:43 GMT
From: Ilmari Karonen <iltzu@sci.invalid>
Subject: Re: Tanspose rows to columns
Message-Id: <959008533.25755@itz.pp.sci.fi>

In article <B54DE01A.A158%xah@xahlee.org>, Xah wrote:
>> Oh, *there* it is... and blech! It builds a string for eval() every time
>> it's called. That ought to make it run nice & slow.
>
>>Was that the only way you could find to do it?
>
>Yes, and if you could show me it without eval i would sprawl and bark like a
>dog for your entertainment. I'll show that, how one of us, is utterly
>willing but not able. Honest. I'll give you Perl folks 1 week.

The whole module, or just the transpose part?  I'm not going to wade
through all the 70kb of code to remove eval()s, but that single one
isn't hard to eliminate - in fact, I don't see why it should be there
in the first place, when an auxiliary function is so much easier:

  # warning: untested code
  sub _subnode ($@) {
      my ($node, @indices) = @_;
      $node = $node[shift @indices] while @indices;
      return \$node;
  }
 
  sub _transposeFullArgs ($$) {
      my $ref_tree = $_[0];
      my $ref_perm = $_[1];
    
      my $transposeLevel = scalar @$ref_perm;
      my $ref_indexSet = [grep {scalar @$_ == $transposeLevel} @{ _completeIndexSet([map {$_ = $_->[0];} @{ _treeToIndexSet($ref_tree)}]) }];
    
      my $ref_resultTree;
      foreach my $ref_index (@$ref_indexSet) {
          # warning: untested code
	  ${_subnode($ref_resultTree, @{Permute($ref_index,$ref_perm)})} = ${_subnode($ref_tree, @$ref_index)};
      }
      return $ref_resultTree;
  }

But that still seems like an inefficient way to do it, since it has to
descend the tree to get each leaf, just like your original.  I think a
recursive approach would be more efficient for large trees.

-- 
Ilmari Karonen - http://www.sci.fi/~iltzu/
Please ignore Godzilla and its pseudonyms - do not feed the troll.



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

Date: Mon, 22 May 2000 15:18:24 GMT
From: bart.lateur@skynet.be (Bart Lateur)
Subject: Re: Untaint URL character class
Message-Id: <392b4f7f.745606@news.skynet.be>

Godzilla! wrote:

>"There are, of course, some obscure exceptions
> which may need to be added to each...make note
> of their exceptions, if you think you need those 
> exceptions."

>Leaving out as many characters as 'reasonably'
>possible, lends to better security. Being both
>realistic and reasonable, is of key importance 
>in good programming practices.

'%' is not an obscure exception. It is THE standard way to escape
dangerous characters.

-- 
	Bart.


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

Date: Mon, 22 May 2000 09:03:04 -0700
From: "Godzilla!" <godzilla@stomp.stomp.tokyo>
Subject: Re: Untaint URL character class
Message-Id: <39295A38.2575015B@stomp.stomp.tokyo>

Bart Lateur wrote:
> Godzilla! wrote:
 
> >"There are, of course, some obscure exceptions
> > which may need to be added to each...make note
> > of their exceptions, if you think you need those
> > exceptions."
 
> >Leaving out as many characters as 'reasonably'
> >possible, lends to better security. Being both
> >realistic and reasonable, is of key importance
> >in good programming practices.
 
> '%' is not an obscure exception. It is THE standard 
> way to escape dangerous characters.


Yeah ok. Don't get all excited on us. I've noticed
over forty million internet users, especially those
of America Onlame, use % quite frequently in an URL.
No problem. Relax dude. You can have it your way.

Next time I need to escape a dangerous character,
such as myself, I will use % to escape, sointly.

Godzilla!


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

Date: Mon, 22 May 2000 08:21:21 -0700
From: "Godzilla!" <godzilla@stomp.stomp.tokyo>
Subject: Re: updated : Re: regexes *sigh* damn I hate these things
Message-Id: <39295071.83798E10@stomp.stomp.tokyo>

The WebDragon wrote:
 
> the problem has become more complex than it was.
 
> I now need to make sure to extract TWO values 
> from this file 

(lots of snippage)


Your solution is still very simple.

*demure smile*


Incidently, do you know Father Burntureally?

*demur smile*



Godzilla!


PRINTED RESULTS:
________________


Game cyberwar has a popularity rating of 7.5. 

Game nitro has a popularity rating of 9. 

Game Cyberwar has a popularity rating of 7.5. 

Game Nitro has a popularity rating of 9. 


TEST SCRIPT:
________________

#!/usr/local/bin/perl

print "Content-Type: text/plain\n\n";

$Pretend_Input1 = "Name:  <a href=\"http://www.planetunreal.com/dl/
 nc.asp? nalicity/utdm/dm-cyberwar.zip\">DM-Cyberwar</a><br>\n\n
 Author:  <a href=\"mailto:666deadman666\@email.msn.com\">deadman
 </a><br>\n\n Rating: (1-10) 7.5 <p></p>\n";

$Pretend_Input2 = "<p>Name:  <a href=\"http://www.planetunreal.com/dl/
 nc.asp?nalicity/\n utdm/dm-nitro.zip\">DM-Nitro</a><br>\n Author:
 <a href=\"mailto:ebolt\@planetunreal.com\">Eric \'Ebolt\' Boltjes</a>
 <br>\n Rating: (1-10) 9</p><!-- add correct image name below here
-->\n";

if ($Pretend_Input1 =~ /dm-([a-z]+)\./)
  { $game = $1; }
if ($Pretend_Input1 =~ / ([0-9\.]+)/)
   { $rating = $1; }

print "Game $game has a popularity rating of $rating. \n\n";

if ($Pretend_Input2 =~ /dm-([a-z]+)\./)
  { $game = $1; }
if ($Pretend_Input2 =~ / ([0-9\.]+)/)
   { $rating = $1; }

print "Game $game has a popularity rating of $rating. \n\n";

## Another way:

if ($Pretend_Input1 =~ /DM-([A-Z][a-z]+)/)
  { $game = $1; }
if ($Pretend_Input1 =~ / ([0-9\.]+)/)
   { $rating = $1; }

print "Game $game has a popularity rating of $rating. \n\n";

if ($Pretend_Input2 =~ /DM-([A-Z][a-z]+)/)
  { $game = $1; }
if ($Pretend_Input2 =~ / ([0-9\.]+)/)
   { $rating = $1; }

print "Game $game has a popularity rating of $rating. \n\n";

exit;


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

Date: Mon, 22 May 2000 15:55:52 GMT
From: bart.lateur@skynet.be (Bart Lateur)
Subject: Re: Using DBM for simple database?
Message-Id: <392d5320.1674773@news.skynet.be>

Kragen Sitaker wrote:

>DBM files store strings.  So you can encode your thing as a string:
>
>$books{$unique_id} = join ',', $title, $author, $whatever;
># . . . 
>my ($title, $author, $whatever) = split /,/, $books{$another_unique_id};

Sniff... sniff...  I smell Perl4!

-- 
	Bart.


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

Date: Mon, 22 May 2000 10:33:49 -0700
From: Tom Phoenix <rootbeer@redcat.com>
Subject: Re: Using several remote shell commands in print FILEHANDLE "rsh..."
Message-Id: <Pine.GSO.4.10.10005221032200.23375-100000@user2.teleport.com>

On Fri, 19 May 2000, Michael Abramowski wrote:

> Although
> 
>     rsh -l username 192.168.0.2 'HOME=/home/username/tmp; env'
> 
> works fine from an interactive shell, I have trouble using a command
> like that in my Perl script, because Perl interprets the ";" as line
> end.

Perl won't do that, if you've quoted that string properly. I think you
haven't. :-)

But you may want the Expect module. Cheers!

-- 
Tom Phoenix       Perl Training and Hacking       Esperanto
Randal Schwartz Case:     http://www.rahul.net/jeffrey/ovs/



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

Date: 22 May 2000 17:04:53 GMT
From: abigail@foad.org (Abigail)
Subject: Re: valid email address
Message-Id: <slrn8iiq5l.1bm.abigail@ucan.foad.org>

On 22 May 2000 01:51:00 GMT,
Neil Kandalgaonkar <nj_kanda@alcor.concordia.ca> wrote:
++ In article <392b6625.7112622@news.skynet.be>,
++ Bart Lateur <bart.lateur@skynet.be> wrote:
++ >Neil Kandalgaonkar wrote:
++ >
++ >>Finaly, the reliably ingenious Abigail has written a module which 
++ >>uses Parse::RecDescent to check addresses against RFC 822.
++ >>It's slow but it seems to work, although
++ >>the test script shows it misses a few cases. Running the test script
++ >>with --debug shows just how insanely complex the spec is.
++ >
++ >Now I'm curious. Examples, please?
++ 
++ They're all in the test script, test.pl, in the package mentioned.

*growl* That was fixed, uploaded on CPAN, but it seems it never made it
to the appropriate directory.



Abigail


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

Date: 22 May 2000 17:08:46 GMT
From: abigail@foad.org (Abigail)
Subject: Re: valid email address
Message-Id: <slrn8iiqcu.1bm.abigail@ucan.foad.org>

On 21 May 2000 15:54:38 GMT,
Neil Kandalgaonkar <nj_kanda@alcor.concordia.ca> wrote:
++   
++ Finaly, the reliably ingenious Abigail has written a module which 
++ uses Parse::RecDescent to check addresses against RFC 822. Please
++ forgive me if this module is not meant to be released, it
++ only seems to be available in her personal CPAN directory under
++ RFC::RFC822::Address.pm.


The CPAN namespace seems to be controlled by a closed mailing list,
using unpublished guidelines.

I no longer bother begging them for top level links. With trivial
digging, all the information can be found in modulelist files
anyway.



Abigail


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

Date: Mon, 22 May 2000 08:22:37 -0700
From: bjanko <waldo700NOwaSPAM@aol.com.invalid>
Subject: Re: What's this line which Perl added to AUTOEXEC.BAT?
Message-Id: <0a2a1d9c.26c42e7a@usw-ex0102-016.remarq.com>

Unfortunately, I no longer have the original autoexec.bat.  Upon
rebooting the PATH in the original seemed to have been
overwritten.  I can only tell you that I have restored the sum
total of my Autoexec.bat to the following:

@C:\PROGRA~1\NORTON~1\NAVDX.EXE /Startup
@ECHO OFF
@DOSKEY
@PATH C:\WINDOWS;C:\PERL\BIN


* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!



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

Date: 22 May 2000 17:31:45 +0100
From: nobull@mail.com
Subject: Re: Windows/Linux Incompatibility
Message-Id: <u97lcmr1fy.fsf@wcl-l.bham.ac.uk>

"Blair Heuer" <ab@cd.com> writes:

> I have only programmed perl for and on Windows machines, but today my server
> administrator switched the server to Linux. ( Hooray for Linux! )

> I have narrowed the problem down to being that the script leaves a return of
> some sort after every variable which are taken from a file which seperates
> variables by line. The code is then chomped, so it should not have any
> problems, right?

Looks like you forget to transfer the files as text when you copied
them from Windows to Unix.  

chomp() does the right thing for the platform it's running on.  It
does not cope with text files copied as binary from a different
platform.

-- 
     \\   ( )
  .  _\\__[oo
 .__/  \\ /\@
 .  l___\\
  # ll  l\\
 ###LL  LL\\


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

Date: 16 Sep 99 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 16 Sep 99)
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: The mail to news gateway, and thus the ability to submit articles
| through this service to the newsgroup, has been removed. I do not have
| time to individually vet each article to make sure that someone isn't
| abusing the service, and I no longer have any desire to waste my time
| dealing with the campus admins when some fool complains to them about an
| article that has come through the gateway instead of complaining
| to the source.

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 V9 Issue 3124
**************************************


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