[19648] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 1843 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sat Sep 29 18:05:39 2001

Date: Sat, 29 Sep 2001 15:05:07 -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: <1001801106-v10-i1843@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Sat, 29 Sep 2001     Volume: 10 Number: 1843

Today's topics:
    Re: AoA(LoL) Sorting <goldbb2@earthlink.net>
    Re: How can I use a filehandle indirectly? <goldbb2@earthlink.net>
    Re: including local file in .cgi <tony_curtis32@yahoo.com>
    Re: including local file in .cgi <michael@heiming.de>
    Re: including local file in .cgi nobull@mail.com
    Re: open EXPR, EXPR and strict 'refs' nobull@mail.com
        Pattern Matching (shaz)
    Re: Pattern Matching (F. Xavier Noria)
    Re: Perl running slow... <goldbb2@earthlink.net>
    Re: Problem executing pgp.exe with systemfunction nobull@mail.com
    Re: Running system programs from CGI (Randal L. Schwartz)
    Re: script timing out nobull@mail.com
    Re: Security of letting user specify regex in CGI scrip <goldbb2@earthlink.net>
    Re: sendmail gadget works on one server, not on another <goldbb2@earthlink.net>
        Sorting multidimensional arrays and MIN/MAX <bigusAT@btinternetDOT.com>
    Re: Sorting multidimensional arrays and MIN/MAX <tsee@gmx.net>
    Re: Sorting multidimensional arrays and MIN/MAX (Garry Williams)
    Re: Statistics::Descriptive Question <comdog@panix.com>
    Re: Statistics::Descriptive Question <comdog@panix.com>
    Re: Works sometimes - tmadmin <goldbb2@earthlink.net>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Sat, 29 Sep 2001 17:27:12 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: AoA(LoL) Sorting
Message-Id: <3BB63CB0.608D706D@earthlink.net>

Jonathan Clover wrote:
> 
> Okay I have the folowing code below that reads in the Log file similar
> to that which is also appended below into an array of an array (or
> list of list).  Now I really want to accomplish the task of sorting
> this table(of sorts) by the user column, but am unsure on how to
> accomplish such a task.
> Please help!

Considering the size, you might want to use an external sort, rather
than an in-memory sort.

> Jonathan Clover
> NATI
> P.S. The actual log file of which will be read in is currently 788 lines and
> growing.
> 
> ########
> ##CODE##
> ########
> #!/usr/bin/perl -w
> use strict;
> use Fcntl qw( :DEFAULT :flock);
> 
> open (TEMP, "cpg/logs/movement_log.dat") || die("Cannot open temporary
> file(1): ".$!);
> flock(TEMP, LOCK_EX) || die("Cannot flock movement_log file(1): ".$!);
> 
> my (@tmp, @log);
> my ($i, $j);
> while(<TEMP>) { ###Print out Movement Log###
>    chomp($_);
>    @tmp = split /, /, $_;
>    push @log, [ @tmp ];
> }

#!/usr/bin/perl -w
use strict;
use Fcntl qw(:flock);
use IPC::Open2;

open( UNSORTED, "<cpg/logs/movement_log.dat" )
	or die "Couldn't open logfile : $!";
flock UNSORTED, LOCK_SH # we're reading, not writing, so SH, not EX.
	or die "Couldn't flock logfile : $!";
<UNSORTED>; # discard first line.
sysseek( UNSORTED, tell(UNSORTED), 0 ); # magic
my $pid = open2( SORTED, "<&UNSORTED",  qw(sort -t, -k2) );
print while <SORTED>;
close SORTED;
if( waitpid $pid, 0 ) {
	my ($sig, $ret) = ( $?&255, $?>>8 );
	die "sort died from signal $sig" if $sig;
	die "sort exited with code $ret" if $ret;
} else {
	die "waitpid($pid) failed: $!";
}

NB: this code is untested.  It's possible that in passing the filehandle
to open2, the file lock is lost.  That would be bad.  In that case:

#!/usr/bin/perl -w
use strict;
use Fcntl qw(:flock);
use IPC::Open2;

open( UNSORTED, "<cpg/logs/movement_log.dat" )
	or die "Couldn't open logfile : $!";
flock UNSORTED, LOCK_SH # we're reading, not writing, so SH, not EX.
	or die "Couldn't flock logfile : $!";
<UNSORTED>; # discard first line
my $pid = open2( SORTED, TO_SORT,  qw(sort -t, -k2) );
print TO_SORT while <UNSORTED>;
close TO_SORT;
close UNSORTED;
print while <SORTED>;
close SORTED;
if( waitpid $pid, 0 ) {
	my ($sig, $ret) = ( $?&255, $?>>8 );
	die "sort died from signal $sig" if $sig;
	die "sort exited with code $ret" if $ret;
} else {
	die "waitpid($pid) failed: $!";
}

You might also want to considering using DBI and DBD::CSV.

-- 
"I think not," said Descartes, and promptly disappeared.


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

Date: Sat, 29 Sep 2001 15:20:42 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: How can I use a filehandle indirectly?
Message-Id: <3BB61F0A.FB0BA957@earthlink.net>

W K wrote:
> 
> >   How can I use a filehandle indirectly?
> >
> >     An indirect filehandle is using something other than a symbol in
> >     a place that a filehandle is expected. Here are ways to get
> >     indirect filehandles:
> >
> >         $fh =   SOME_FH;       # bareword is strict-subs hostile
> >         $fh =  "SOME_FH";      # strict-refs hostile; same package only
> >         $fh =  *SOME_FH;       # typeglob
> >         $fh = \*SOME_FH;       # ref to typeglob (bless-able)
> >         $fh =  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH typeglob
> 
> I was under the impression that we didn't need to worry about how it works,
> from 5.6 onwards
> just
> open ($fh ,"afile") or die "In pain $!";

Many older sites only have 5.0.  Do you really want to always limit your
programs to *only* work with the newest version of perl?

-- 
"I think not," said Descartes, and promptly disappeared.


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

Date: Sat, 29 Sep 2001 11:49:53 -0500
From: Tony Curtis <tony_curtis32@yahoo.com>
Subject: Re: including local file in .cgi
Message-Id: <87adze2b7y.fsf@limey.hpcc.uh.edu>

>> On Sat, 29 Sep 2001 16:11:35 +0200,
>> Michael Heiming <michael@heiming.de> said:

> parts are displayed, some are not. That's the file
> ($htmltext) that should be included:

> ACTION="/cgi-bin/display.cgi" METHOD="POST"> <TEXTAREA
> NAME="text" COLS=100 ROWS=10>\n$text</TEXTAREA>
> <BR>Check<INPUT TYPE="checkbox" $status NAME="ENABLE"

> The problem is the text box which doesn't display $text,
> which is known by the cgi, it's read from another
> file. Case the above lines are direct in "display.cgi"
> it works perfectly.

You're asking perl to read text from a file and output it
to the HTML stream.  Which it does as expected.  The
string "$text" in the input file is output as it is read.
(If the string is included literally within the program
then it undergoes some further evaluation including
variable interpolation when the code is compiled.  Text
read in from a file is not part of the compiled program at
all.)

What you actually want is to for some of the text read
from the file to be interpreted as perl variables and for
their values to be interpolated into the output.

I have the feeling there must be a nice clean way of doing
this with one of the core perl modules, but can someone
help me out?  I won't pollute the archive space of clpm
with a hacked up piece of parsing code if so.

-- 
Yes way!  Mmmmkay?


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

Date: Sat, 29 Sep 2001 19:06:13 +0200
From: Michael Heiming <michael@heiming.de>
Subject: Re: including local file in .cgi
Message-Id: <62v4p9.j06.ln@charon.heiming.de>

Tony Curtis (tony_curtis32@yahoo.com) wrote at Saturday 29 September 
2001 18:49:

>>> On Sat, 29 Sep 2001 16:11:35 +0200,
>>> Michael Heiming <michael@heiming.de> said:
> 
>> parts are displayed, some are not. That's the file
>> ($htmltext) that should be included:
> 
>> ACTION="/cgi-bin/display.cgi" METHOD="POST"> <TEXTAREA
>> NAME="text" COLS=100 ROWS=10>\n$text</TEXTAREA>
>> <BR>Check<INPUT TYPE="checkbox" $status NAME="ENABLE"
> 
>> The problem is the text box which doesn't display $text,
>> which is known by the cgi, it's read from another
>> file. Case the above lines are direct in "display.cgi"
>> it works perfectly.
> 
> You're asking perl to read text from a file and output it
> to the HTML stream.  Which it does as expected.  The
> string "$text" in the input file is output as it is read.
> (If the string is included literally within the program
> then it undergoes some further evaluation including
> variable interpolation when the code is compiled.  Text
> read in from a file is not part of the compiled program at
> all.)
> 
> What you actually want is to for some of the text read
> from the file to be interpreted as perl variables and for
> their values to be interpolated into the output.
> 
> I have the feeling there must be a nice clean way of doing
> this with one of the core perl modules, but can someone
> help me out?  I won't pollute the archive space of clpm
> with a hacked up piece of parsing code if so.

Many thanks, just put the part with $text back in the cgi and load 
the rest from a file, that did the trick (don't need $text in the 
included ASCII file)....forget about nice/clean...:-)

Thx

Michael Heiming


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

Date: 29 Sep 2001 18:31:29 +0100
From: nobull@mail.com
Subject: Re: including local file in .cgi
Message-Id: <u9ite1ykcu.fsf@wcl-l.bham.ac.uk>

Michael Heiming <michael@heiming.de> writes:

> That's the file ($htmltext) that should be 
> included:
> 
> <HTML>
> <HEAD>
> <TITLE>Title</TITLE>
> </HEAD>
> <BODY BGCOLOR=#FFFFFF>
> <IMG ALT="graph" 
> SRC="http://my.hostname/cgi-bin/perf.cgi?log=last&png=small">
> <TABLE BORDER=0 CELLSPACING=2 CELLPADDING=0>
> <TR BGCOLOR=#AAAAAA>
>  <TD>
>   <FORM ACTION="/cgi-bin/display.cgi" METHOD="POST">
>    <TEXTAREA NAME="text" COLS=100 ROWS=10>\n$text</TEXTAREA>
>    <BR>Check<INPUT TYPE="checkbox" $status NAME="ENABLE" VALUE="yes">
>    <INPUT TYPE="submit" NAME="Save" VALUE="SAVE">
>   </FORM>
>  </TD>
> </TR>
> </TABLE>
> </BODY>
> </HTML>
> 
> The problem is the text box which doesn't display $text, which is 
> known by the cgi, it's read from another file. Case the above lines 
> are direct in "display.cgi" it works perfectly.

Ah...! So this is a very ofuscated way of asking (FAQ) "How can I
expand variables in text strings?"

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


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

Date: 29 Sep 2001 18:34:37 +0100
From: nobull@mail.com
Subject: Re: open EXPR, EXPR and strict 'refs'
Message-Id: <u9g095yk7m.fsf@wcl-l.bham.ac.uk>

Joe Schaefer <joe+usenet@sunstarsys.com> writes:

>   % perldoc -f open
>        open FILEHANDLE,MODE,LIST
>        open FILEHANDLE,EXPR
>        open FILEHANDLE
>                Opens the file whose filename is given by EXPR,
>                and associates it with FILEHANDLE.  If FILEHANDLE
>                is an expression, its value is used as the name of
>                the real filehandle wanted.  (This is considered a
>                symbolic reference, so "use strict 'refs'" should
>                not be in effect.)

>   % perl -Mstrict -wle 'open "mydata", ">&STDOUT"; print mydata "foo"'
>   Unquoted string "mydata" may clash with future reserved word at -e line 1.
>   foo

> Perhaps the parenthetical should read something like:
> 
>                                ...  (Although not enforced by
>            "use strict 'refs'", this value is considered a 
>            symbolic reference- see the perlreftut and perlref 
>            manpages for details.)

IMNSHO the behaviour is buggy not the manual.

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


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

Date: 29 Sep 2001 09:29:41 -0700
From: ssa1701@yahoo.co.uk (shaz)
Subject: Pattern Matching
Message-Id: <23e71812.0109290829.145aff2b@posting.google.com>

The basic problem i am having is looking for strings withing longer
strings.

%strings has a number of strings stored as keys (i know it is not how
it should be done).

what i want to do is to see if certain smaller strings ($small) are
present in %strings.

$look = /[$small]/;

if (exists $strings{$look})
{...}

but I keep getting "uninitialised value in pattern match".

Any ideas where i am going wrong????


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

Date: 29 Sep 2001 16:51:43 GMT
From: fxn@retemail.es (F. Xavier Noria)
Subject: Re: Pattern Matching
Message-Id: <9p4u6v$4pvrn10@news1s.iddeo2.es>

On 29 Sep 2001 09:29:41 -0700, shaz <ssa1701@yahoo.co.uk> wrote:

: The basic problem i am having is looking for strings withing longer
: strings.
: 
: %strings has a number of strings stored as keys (i know it is not how
: it should be done).
: 
: what i want to do is to see if certain smaller strings ($small) are
: present in %strings.

If I understand it correctly, you want a test for the existence of a
given substring within any of the keys of the hash %strings.

I don't understand your code quite well, but this is how I'd do it:

    $small  = 'foo';
    $y_or_n = grep { index($_, $small) != -1 } keys %strings;

-- fxn


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

Date: Sat, 29 Sep 2001 18:06:18 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Perl running slow...
Message-Id: <3BB645DA.C590B3E5@earthlink.net>

Adam wrote:
> 
> Using some simple benchmarks, I am having problems with Perl 5.6 on a
> cobalt raq3 (running redhat -- not cobalt linux).  Using a simple  use
> CGI and a print loop, I have yeilded the following:
[snip]
> Whenever a script is ran, it has a few seconds of nothing, just
> startup overhead.  If anyone has any information on why, I would be
> very thankful.

CGI.pm and DBI.pm are gargantuan, and take a while to load.  If you've
scripts with them which are going to get a really high load, then you
should be using either mod_fastcgi or mod_perl.  

Both reduce your overhead by making the script persistant, so it only
loads once.  mod_fastcgi works by sortof making each script into it's
own mini-server.  mod_perl works by having a perl interpreter embeded
into the apache server, and making each script into a function.  I
believe that mod_perl is faster overall, if you have many different
scripts, but you can get wierd, wonky errors like "variable will not
stay shared," and [I've heard] it's harder to install.  Scripts written
to use mod_fastcgi are easier to understand; you can easily see how and
why they're persistant -- there're fewer things happening behind the
scenes.

An example mod_perl script might look like:
# can't turn on taint checking, as far as I know.
use DBI;
use CGI;
use strict;
use warnings;
our $dbh ||= DBI->connect( ... );
our $sth ||= $dbh->prepare( ... );
my $cgi = CGI->new;
print $cgi->header, $cgi->begin_html;
my $table =
	$sth->execute( $cgi->param("foo"), $cgi->param("bar") )
	&& $sth->fetchall_arrayref;
if( $table ) {
	print table( Tr [map td($_), @$table] );
} else {
	print blink( $DBI::errstr );
}
print end_html;
__END__

An example mod_fastcgi script might look like:
#!/usr/local/bin/perl -wT
use DBI;
use CGI::Fast;
use strict;
my $dbh = DBI->connect( ... );
my $sth = $dbh->prepare( ... );
while( my $cgi = CGI::Fast->new ) {
	print $cgi->header, $cgi->begin_html;
	my $table =
		$sth->execute( $cgi->param("foo"), $cgi->param("bar") )
		&& $sth->fetchall_arrayref;
	if( $table ) {
		print table( Tr [map td($_), @$table] );
	} else {
		print blink( $DBI::errstr );
	}
	print end_html;
}
__END__

They're very similar, of course, but can you see in the mod_perl script
exactly why I use "our" instead of "my" for the $dbh and $sth, and why I
used "||=" ?  I need no such nonsense in the mod_fastcgi script.  Also,
it is quite clear exactly how and why the fastcgi script is persistant
 ... there's a "while" loop in it!  There's no such obvious reason for
the mod_perl script to be persistant.

Although there are none in this, mod_perl scripts often have to be
carefully written to avoid "variable will not stay shared" warnings from
when a you write a sub which uses a my variable from the enclosing scope
[even if it looks like it's at the 'file level' scope, it's not, since
mod_perl scripts are actually made into subroutines].

Also, if your script does something which leaks or corrupts memory, it
will end up screwing with the apache server if it's done via mod_perl,
but only that one program if it's mod_fastcgi.

And of course I don't know of how you can turn on taint checking for
mod_perl.

-- 
"I think not," said Descartes, and promptly disappeared.


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

Date: 29 Sep 2001 18:07:21 +0100
From: nobull@mail.com
Subject: Re: Problem executing pgp.exe with systemfunction
Message-Id: <u9ite20vud.fsf@wcl-l.bham.ac.uk>

"Alastair Martindale" <alastairm_news@cogapp.com> writes:

>     print system "$pgpprog $PGP_ARGS";

> I think result=5376 means that pgp.exe has executed but returned an error of
> 21. When I run the same command in the DOS prompt the program executes
> without problem.

Does 'without problem' == 'without returning an error level of 21'.
 
> Is there something obvious I have overlooked?

Dunno - what error code did it return in DOS.


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

Date: 29 Sep 2001 09:30:50 -0700
From: merlyn@stonehenge.com (Randal L. Schwartz)
Subject: Re: Running system programs from CGI
Message-Id: <m166a2j6x1.fsf@halfdome.holdit.com>

>>>>> "Jim" == Jim Britain <jbritain@home.com> writes:

Jim> The problem is that most modern Unix like OSs will not run
Jim> scripts as SUID programs -- they end up being big security
Jim> hole/targets..  The OSs will run compiled programs only..

It's interesting how the histories have gone on this.

In the very old Unix days, setuid didn't work on scripts.

Then the boyz at Bezerkely added #!, with one of the benefits being
that scripts could finally be setuid!  Yeay!

Then the Evil Ones figured out that most shell scripting was not very
secure (invoking csh without -f was my favorite one, but the symlink
swapping trick was universally available), so setuid scripts were
bad again.  Boo!

So then many kernels stopped supporting setuid scripts.  In parallel
with that, some shells specificly forbid seteuid(0) so that at least
root wouldn't be compromised.  Yeay!

But someone came up with the idea to use /dev/fd/3 (I think that's it)
to pass the script of #!/usr/bin/scripter script, and then the symlink
trick no longer works, so setuid scripts could be turned back on, and
relatively securely, YEAY!

Just a bit of history for you young'uns.

Just another Unix hacker since 1977 (yes *77*),

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!


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

Date: 29 Sep 2001 18:21:00 +0100
From: nobull@mail.com
Subject: Re: script timing out
Message-Id: <u9lmixykub.fsf@wcl-l.bham.ac.uk>

"Zachary Kent" <zkent@adelphia.net> writes:

> "Logan Shaw" <logan@cs.utexas.edu> wrote in message
> news:9p2lhe$3j8$1@charity.cs.utexas.edu...
> > In article <GC2t7.2978$4Y1.2267074@news1.news.adelphia.net>,
> > Zachary Kent <zkent@adelphia.net> wrote:
> > >I have a client whose server times out scripts after 10 seconds.
> 
> > > How can I
> > >keep override the servers timeout settings using Perl?
> >
> > You probably can't, but then again maybe you can, because it all
> > depends on what you're talking about.
> 
> Well, I didn't think so. But, I am looking at using autoflush to send an
> immediate response to the browser so that the server does not kill the
> script before the script begins the output.  Think that would help?

There are various tricks that you can use in CGI scripts to get
arround slow operations.  These tricks are essentially independant of
the language used to implement the scripts.  Try looking in the
newsgroups where CGI programming is discussed where you will find
there's rarely not an ongoing thread on this question.

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


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

Date: Sat, 29 Sep 2001 15:15:35 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Security of letting user specify regex in CGI script?
Message-Id: <3BB61DD7.BEE850E0@earthlink.net>

Jay McGavren wrote:
> 
> > I think Text::Query goes in the right direction, though I haven't
> > tried it myself.
> 
> Aha!  It looks perfect!
> 
> > BTW there's no need to create one regex of it. After all, perl knows
> > eval, so it's easy to create a sub that checks if a string matches
> > your requirements. For example, "a and (b or c)" can be converted to
> >
> >       $query = eval "sub { /\ba\b/ and (/\bb\b/ or /\bc\b/ }";
> 
> True, but letting the user specify any portion of an eval gives me the
> jitters.

The solution then is to either not do that, or to use quotemeta:

my $query = "a and (b or c)";
my @words = split /((?:\s*(?:[()]|\band\b|\bor\b)\s*)+)/, $query;
my $eval = "";
for my $i ( 0 .. $#words ) {
	if( $i & 1 ) {
		$eval .= $words[$i]; # (, ), and, or or.
	} else {
		#$eval .= ' m[\b$words[' . $i . ']\b] ';
		#produces eval 'sub { m[\b$words[0]\b] and ( ...';
		$eval .= " m[\\b\Q$words[$i]\E\\b] ";
	}
}
my $query = eval "sub {$eval}";

Surrounding the literal sections in \Q\E should make it safe to eval.

-- 
"I think not," said Descartes, and promptly disappeared.


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

Date: Sat, 29 Sep 2001 14:56:00 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: sendmail gadget works on one server, not on another
Message-Id: <3BB61940.F76992B4@earthlink.net>

Fat Boy wrote:
> 
> Hi there
> 
> I had this part of a shopping cart working on one host (best.com) but
> not on another (verio.com) and they can't help.
> 
> Check it out:
> 
> I apologixe this is so long, but really I've busted my nuts trying to
> find out why it doesn't work anymore. My greatest appreciation for
> anyone who could take a look and offer some suggestions.

What you have is a perl4 library.  Instead of asking why it *doesn't*
work, you should be trying to figure out why it *did* work, and look
for, or write, a perl5 module which does the same or equivilant.

-- 
"I think not," said Descartes, and promptly disappeared.


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

Date: Sat, 29 Sep 2001 18:20:35 +0100
From: "S Warhurst" <bigusAT@btinternetDOT.com>
Subject: Sorting multidimensional arrays and MIN/MAX
Message-Id: <9p4vqg$dg4$1@neptunium.btinternet.com>

Hi.. please can you help... I'm not finding Perl very user-friendly with
regard to sorting, and am having trouble finding a way of doing the
following:

Multidimensional arrays
------------------------
If I have an two-dimensional array like this:

@array = ( [1,100] ,
                  [2,120] ,
                  [3,100] ,
                  [4,110] );

and I want to sort it by column 2 so that it looks like this:

@array = ( [1,100] ,
                  [3,100] ,
                  [2,110] ,
                  [4,120] );

How do I go about it?

MIN/MAX
------------
Using the above array as an example, if I wanted to find out the MIN or MAX
values in column 2, is there simple command to do it, or do I have to either
sort or loop through the column (assuming it can be done) first?

Thanks

¦                 ¦--¦
¦--¦- Bigus -¦--¦
¦--¦






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

Date: Sat, 29 Sep 2001 20:13:43 +0200
From: "Steffen Müller" <tsee@gmx.net>
Subject: Re: Sorting multidimensional arrays and MIN/MAX
Message-Id: <9p5359$pqh$04$1@news.t-online.com>

"S Warhurst" <bigusAT@btinternetDOT.com> schrieb im Newsbeitrag
news:9p4vqg$dg4$1@neptunium.btinternet.com...
> Hi.. please can you help... I'm not finding Perl very user-friendly with
> regard to sorting, and am having trouble finding a way of doing the
> following:

It is not user friendly. It is programmer friendly.
Anyway, you could read the FAQ, the manual, search google, the web, or just
ask for our help as you did. However, I suggest you start with the first in
the list and ask last.

> @array = ( [1,100] ,
>                   [2,120] ,
>                   [3,100] ,
>                   [4,110] );
>
> and I want to sort it by column 2 so that it looks like this:
>
> @array = ( [1,100] ,
>                   [3,100] ,
>                   [2,110] ,
>                   [4,120] );
>
> How do I go about it?

@array = sort { $a->[1] <=> $b->[1] } @array;
#                    ^           ^
#                   second element!

see perldoc perlfunc
(perldoc sort)

If you want to sort by the second AND the first column, look at FAQ 4.

> MIN/MAX
> ------------
> Using the above array as an example, if I wanted to find out the MIN or
MAX
> values in column 2, is there simple command to do it, or do I have to
either
> sort or loop through the column (assuming it can be done) first?

Even if there was such a command, it'd have to loop through the data
somehow.

# untested, but should work with warnings and strict.

my ( $min, $max ) = ( $array[0][1] );
foreach ( @array ) {
   $min = $_[1] if $_[1] < $min;
   $max = $_[1] if $_[1] > $max;
}

Hope this helps.
Steffen





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

Date: Sat, 29 Sep 2001 18:45:51 GMT
From: garry@ifr.zvolve.net (Garry Williams)
Subject: Re: Sorting multidimensional arrays and MIN/MAX
Message-Id: <slrn9rc5mu.ass.garry@zfw.zvolve.net>

On Sat, 29 Sep 2001 18:20:35 +0100, S Warhurst
<bigusAT@btinternetDOT.com> wrote:

> Hi.. please can you help... I'm not finding Perl very user-friendly
> with regard to sorting, and am having trouble finding a way of doing
> the following:

That's because you apparently have not bothered to consult the Perl
FAQ.  

> Multidimensional arrays
> ------------------------
> If I have an two-dimensional array like this:
> 
> @array = ( [1,100] ,
>                   [2,120] ,
>                   [3,100] ,
>                   [4,110] );
> 
> and I want to sort it by column 2 so that it looks like this:
> 
> @array = ( [1,100] ,
>                   [3,100] ,
>                   [2,110] ,
>                   [4,120] );
> 
> How do I go about it?

Check the perlfaq4 manual page for "How do I sort an array by
(anything)?".  This command prints that section directly: 

  perldoc -q sort

Here's a way: 

  @array = sort { $a->[1] <=> $b->[1] } @array;

See the perlfunc manual page for sort().  

> MIN/MAX
> ------------
> Using the above array as an example, if I wanted to find out the MIN or MAX
> values in column 2, is there simple command to do it, or do I have to either
> sort or loop through the column (assuming it can be done) first?

The perlfunc manual page summarizes all of Perl's functions in a handy
section "Perl Functions by Category".  Since I don't see min/max
there, maybe this will help: 

    sub min_on_column_2 {
	my $min = $_[0];
	for (@_) {
	    $min = $_ if $_->[1] < $min->[1];
	}
	return $min;
    }

The max function is left to the reader.  

-- 
Garry Williams


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

Date: Sat, 29 Sep 2001 12:34:58 -0400
From: brian d foy <comdog@panix.com>
Subject: Re: Statistics::Descriptive Question
Message-Id: <comdog-BDF934.12345829092001@news.panix.com>

In article <Eclt7.1012$M03.93893@typhoon1.gnilink.net>, "Mark Riehl" 
<mark.riehl@agilecommunications.com> wrote:

> All - I'm using the Statistics::Descriptive module under Win2k.  I'd like to
> do the following:

> 1. Create a Stat::Desc object.
> 2. Add values using add_data(), perform calculations.
> 3. Clear the values.
> 4. Add values using add_data(), perform calculations.

> instantiating a new object?

there isn't a way to do that, and even if there was it would be
pretty close to making a new object since it would have to
re-initialize everything.

why not simply make another object?

-- 
brian d foy <comdog@panix.com> - Perl services for hire
CGI Meta FAQ - http://www.perl.org/CGI_MetaFAQ.html
Troubleshooting CGI scripts - http://www.perl.org/troubleshooting_CGI.html



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

Date: Sat, 29 Sep 2001 12:35:46 -0400
From: brian d foy <comdog@panix.com>
Subject: Re: Statistics::Descriptive Question
Message-Id: <comdog-976378.12354629092001@news.panix.com>

In article <APkt7.1000$M03.92526@typhoon1.gnilink.net>, "Mark Riehl" 
<mark.riehl@agilecommunications.com> wrote:

> The stat object contains 1,2,3.  Is there a way to clear the stat object, or
> do I need to create a new one?  For example, now I'd like to calculate the
> mean of 4,5,6.  Can I do it with the same object?  If so, how?

see my answer to the same question in your other post to this group.

-- 
brian d foy <comdog@panix.com> - Perl services for hire
CGI Meta FAQ - http://www.perl.org/CGI_MetaFAQ.html
Troubleshooting CGI scripts - http://www.perl.org/troubleshooting_CGI.html



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

Date: Sat, 29 Sep 2001 16:13:23 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Works sometimes - tmadmin
Message-Id: <3BB62B63.E98F7C81@earthlink.net>

Thomas Bätzler wrote:
> 
> On 26 Sep 2001 07:47:59 -0700, redace1919@yahoo.com (Brian) wrote:
> >open(TUX,"tmadmin <<EOF\nv\npsr\nEOF\n|")  ||
> >         die "Unable to open TUXEDO\n";
> >@tux = <TUX>;
> >close TUX;
> [...]
> >The reason I believe it is something in my script is that while this
> >is happening, if I simply type :
> >tmamdin
> >v
> >psr
> >from unix, I get the info that I expect.
> 
> Looks like your external command chokes at time because you feed it
> its input too fast.

Are you sure?  I thought that when a shell creates a here-doc, it makes
an actual temporary file, in which case the program isn't being "fed"
input, it's reading input at it's own pace.

> A more reasonable way to run this could be to use open2 (see perlipc
> for details) to run your tmadmin program. You could then feed it a
> "v\n" on startup, wait for the expected output and only then send the
> "psr\n". Of course, if tmadmin uses buffered I/O, you may be in a fix
> because you won't see any output from your first command - in that
> case, you could skip that step and instead sleep for a few seconds.

Another possibility is that it wants to read input from a tty.  You can
accomplish this with IPC::Run :

use IPC::Run qw(run);
run [qw(tmadmin)], '<pty<', \"v\npsr\n", \$out;
@tux = split /\n/, $out;

Here're some alternative ways to write the code, which might or might
not be better [these don't create ptys, so if that's the problem then
these definitely won't help]:

@tux = qx[ (echo v; echo psr) | txadmin ];

my $pid = open2( my( $rd, $wr ), "txadmin" );
print $wr "n\npsr\n";
@tux = <$wr>;
waitpid $pid, 0;

open( local(*TEMPFH), "<+", $tempfilename );
print TEMPFH "n\npsr\n";
seek TEMPFH, 0, 0;
my $pid = open2( my($rd, "<&TEMPFH", "txadmin" );
@tux = <$wr>;
waitpid $pid, 0;

NB: None of these are tested.

-- 
"I think not," said Descartes, and promptly disappeared.


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

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.  

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 1843
***************************************


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