[21698] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 3902 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Oct 2 14:11:56 2002

Date: Wed, 2 Oct 2002 11:10:18 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Wed, 2 Oct 2002     Volume: 10 Number: 3902

Today's topics:
        Perl script "rename" does not work... (Joel)
    Re: Perl script "rename" does not work... (Tad McClellan)
    Re: Perl script "rename" does not work... <Tassilo.Parseval@post.rwth-aachen.de>
    Re: Perl script "rename" does not work... (Helgi Briem)
    Re: Perl script "rename" does not work... <nobull@mail.com>
        PERL Socket Woes (Andrew Rich)
    Re: PERL Socket Woes <jhalpin@nortelnetworks.com_.nospam>
    Re: PERL Socket Woes <danb@mail.dnttm.ro>
    Re: PERL Socket Woes <nobull@mail.com>
    Re: reading Cobol PIC 9(6)V99 formats... (Villy Kruse)
    Re: Script stops working when DBI added. Why? <camerond@mail.uca.edu>
    Re: Script stops working when DBI added. Why? <me@me.com>
    Re: Script stops working when DBI added. Why? (Helgi Briem)
    Re: Script stops working when DBI added. Why? <me@me.com>
    Re: Script stops working when DBI added. Why? <wsegrave@mindspring.com>
    Re: Script stops working when DBI added. Why? <me@me.com>
        Sort hash of hash <smileface@libero.it>
    Re: Sort hash of hash <jurgenex@hotmail.com>
    Re: Speed optimization (with code) ctcgag@hotmail.com
        String substitution of 3+ digit numbers only? (Stan Ng)
    Re: String substitution of 3+ digit numbers only? <bernard.el-hagin@DODGE_THISlido-tech.net>
    Re: String substitution of 3+ digit numbers only? <pinyaj@rpi.edu>
        Tab function not working w IE <Wiesen@personnelselection.com>
    Re: Tab function not working w IE <flavell@mail.cern.ch>
    Re: Tab function not working w IE (Tad McClellan)
    Re: Two email things in Perl <alex_perl@tranzoa.com>
    Re: Why are the columns of a MySQL SELECT scrambled? (James)
    Re: Why are the columns of a MySQL SELECT scrambled? <bart.lateur@pandora.be>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: 2 Oct 2002 07:57:13 -0700
From: joel_bearden@hotmail.com (Joel)
Subject: Perl script "rename" does not work...
Message-Id: <5e99ce1d.0210020657.392fdb22@posting.google.com>

Okay, I am about to pull my hair out...

I am building a mysql data directory from a mysql dump file and I need
to change the filenames from lower to uppercase.  Nothing special,
really should be easy that is why I am so frustrated.  I have tried
the rename and the system "mv", as well as several other examples I
have found.  Here is where I am currently at:


 # Converting table names to uppercase.
 print LOGFILE "Converting table names to upper case.\n";
 my($DB_Dir) = '/usr/local/mysql/data/wb_20_test';
 opendir(SYSTEMDIR, $DB_Dir);
 @FileList = readdir(SYSTEMDIR);
 my($oldname);
 my($newname);
 foreach $oldname(@FileList) {
    if (-d $oldname) {     # if . or .., ignore
       next;
    } 
    else {
      $newname = $oldname;
      $newname =~ tr/a-z/A-Z/;
      next if $newname eq $oldname;   # no change necessary
      if(stat($newname)) {
        next;   # Check for duplicate
       };
      # rename ('$DB_Dir/$oldname', '$DB_Dir/$newname);
       system('/bin/sh -c "(/bin/mv -f $DB_Dir/$oldname
$DB_Dir/$newname) 2>&1 1>>Dangit.txt"');
      print LOGFILE "Change ($DB_Dir/$oldname) to
($DB_Dir/$newname).\n";
    };
 };   
 closedir(SYSTEMDIR);


Can anyone provide me some help...  Please...


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

Date: Wed, 02 Oct 2002 15:38:15 GMT
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Perl script "rename" does not work...
Message-Id: <slrnapm4am.33t.tadmc@magna.augustmail.com>

Joel <joel_bearden@hotmail.com> wrote:

> Okay, I am about to pull my hair out...


That is why so many programmers have pony tails.

It is easier to get a good grip.


> I need
> to change the filenames from lower to uppercase.


>  opendir(SYSTEMDIR, $DB_Dir);


Just because you asked for the directory to be opened doesn't
mean you will get what you asked for, so you should check and see:

   opendir(SYSTEMDIR, $DB_Dir) or die "could not opendir '$DB_Dir' $!";


>  @FileList = readdir(SYSTEMDIR);


It is a good habit to get into to free resources as soon as
you are finished with them:

   closedir SYSTEMDIR;


>  my($oldname);
>  my($newname);


Another good habit is to restrict variables to the smallest
possible scope, and to declare them near where you use them.

You do not need for either of those variables to be 
"file global" as you have them.


>  foreach $oldname(@FileList) {


   foreach my $oldname (@FileList) {


You can declare the variable here, where you first use it.


>     if (-d $oldname) {     # if . or .., ignore
>        next;
>     } 


Your comment is misleading. It ignores much more than just
dot and dot-dot.

   next if -d $oldname;   # ignore all directories

But then you'll try and move symlinks and pipes and ...

If you intend to move only plain files, then it would be
best to insure that you only process plain files. So this
is probably better:

   next unless -f $oldname;


>     else {
>       $newname = $oldname;
>       $newname =~ tr/a-z/A-Z/;

Or:

   my $newname = uc $oldname;  # better, it respects locales


>       if(stat($newname)) {
>         next;   # Check for duplicate
>        };


There is a file test for testing existence:


   next if -e $newname;


>       # rename ('$DB_Dir/$oldname', '$DB_Dir/$newname);
                  ^                ^  ^               ^^ hey! wa'happened?


Single quotes do not interpolate. You should see if you got
what you asked for here too:

   rename("$DB_Dir/$oldname", "$DB_Dir/$newname")
      or warn "could not move '$DB_Dir/$oldname' => '$DB_Dir/$newname' $!";


>        system('/bin/sh -c "(/bin/mv -f $DB_Dir/$oldname
> $DB_Dir/$newname) 2>&1 1>>Dangit.txt"');


Since single quotes do not interpolate, $DB_Dir et. al. are
_shell_ variables, not Perl variables.


>  closedir(SYSTEMDIR);


You where finished with it way before here.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: 2 Oct 2002 15:49:58 GMT
From: "Tassilo v. Parseval" <Tassilo.Parseval@post.rwth-aachen.de>
Subject: Re: Perl script "rename" does not work...
Message-Id: <anf4j6$nbl$1@nets3.rz.RWTH-Aachen.DE>

Also sprach Joel:

> Okay, I am about to pull my hair out...
> 
> I am building a mysql data directory from a mysql dump file and I need
> to change the filenames from lower to uppercase.  Nothing special,
> really should be easy that is why I am so frustrated.  I have tried
> the rename and the system "mv", as well as several other examples I
> have found.  Here is where I am currently at:
> 
> 
>  # Converting table names to uppercase.
>  print LOGFILE "Converting table names to upper case.\n";
>  my($DB_Dir) = '/usr/local/mysql/data/wb_20_test';
>  opendir(SYSTEMDIR, $DB_Dir);

   opendir SYSTEMDIR, $DB_Dir or die $!;

These file-operations can go wrong for the most obscure reasons so this
avoids unnecessary debugging.

>  @FileList = readdir(SYSTEMDIR);

   my @FileList = readdir SYSTEMDIR;

Since you later filter out directories, you can do that in one
statement:

    my @FileList = grep { ! -d } readdir SYSTEMDIR;

Also, a good idea might be chaning the for-loop into a while-loop:

    while (my $oldname = readdir SYSTEMDIR) {
        next if -d $oldname;
        ...

Thus, you'd not need @FileList at all.

>  my($oldname);
>  my($newname);

You should declare those variables where you use them. So better ditch
those two lines.

>  foreach $oldname(@FileList) {

   foreach my $oldname (@FileList) { # for instance here...
   
>     if (-d $oldname) {     # if . or .., ignore

You need to prepend the path:

    if (-d "$DB_Dir/$oldname") {

>        next;
>     } 
>     else {
>       $newname = $oldname;

        my $newname = $oldname; # ...and here
        
>       $newname =~ tr/a-z/A-Z/;
>       next if $newname eq $oldname;   # no change necessary
>       if(stat($newname)) {
>         next;   # Check for duplicate
>        };
>       # rename ('$DB_Dir/$oldname', '$DB_Dir/$newname);

This would have worked if you had used interpolating quotes:

    rename "$DB_Dir/$oldname", "$DB_Dir/$newname"
        or die "Error: $DB_Dir/$oldname --> $DB_Dir/$newname : $!";

Once it fails you don't have to make wild guesses why it failed. $! will
tell you why perl was not able to rename the files.

>        system('/bin/sh -c "(/bin/mv -f $DB_Dir/$oldname
> $DB_Dir/$newname) 2>&1 1>>Dangit.txt"');

Here you have again single quotes that do not interpolate the contained
scalar variables. Nonetheless, first try to make rename() work.

>       print LOGFILE "Change ($DB_Dir/$oldname) to
> ($DB_Dir/$newname).\n";
>     };
>  };   
>  closedir(SYSTEMDIR);

Tassilo
-- 
$_=q!",}])(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus;})(rekcah{lrePbus;})(lreP{rehtonabus;})(rehtona{tsuJbus!;
$_=reverse;s/sub/(reverse"bus").chr(32)/xge;tr~\n~~d;eval;


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

Date: Wed, 02 Oct 2002 15:58:43 GMT
From: helgi@decode.is (Helgi Briem)
Subject: Re: Perl script "rename" does not work...
Message-Id: <3d9b163f.2014038464@news.cis.dfn.de>

On 2 Oct 2002 07:57:13 -0700, joel_bearden@hotmail.com
(Joel) wrote:

>Okay, I am about to pull my hair out...

People who do not check the return values from system
commands often do that.  It comes with the territory.

>I am building a mysql data directory from a mysql dump file and I need
>to change the filenames from lower to uppercase.  Nothing special,
>really should be easy that is why I am so frustrated.  I have tried
>the rename and the system "mv", as well as several other examples I
>have found.  Here is where I am currently at:

<SNIP>
>      # rename ('$DB_Dir/$oldname', '$DB_Dir/$newname);

Single quotes do not interpolate!!

The file $DB_Dir/$oldname does not exist as
you would have found out if you had checked $!.
Always, ALWAYS, ALWAYS, check the return value from
system calls, ie

rename "$DB_Dir/$oldname", "$DB_Dir/$newname"
   or die "Cannot rename $DB_Dir/$oldname:$!\n";


-- 
Regards, Helgi Briem
helgi AT decode DOT is

                           A: Top posting
                           Q: What is the most irritating thing on Usenet?
                                           - "Gordon" on apihna


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

Date: 02 Oct 2002 17:42:11 +0100
From: Brian McCauley <nobull@mail.com>
Subject: Re: Perl script "rename" does not work...
Message-Id: <u9fzvookrg.fsf@wcl-l.bham.ac.uk>

joel_bearden@hotmail.com (Joel) writes:

>  my($DB_Dir) = '/usr/local/mysql/data/wb_20_test';
>  opendir(SYSTEMDIR, $DB_Dir);
>  @FileList = readdir(SYSTEMDIR);
>  my($oldname);
>  my($newname);
>  foreach $oldname(@FileList) {
>     if (-d $oldname) {     # if . or .., ignore
>        next;
>     } 

This, I think, is a mistake everyone makes the first time they use
readdir() even though you are explicitly warned about it in the
manual.

See "perldoc -f readdir"

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


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

Date: 2 Oct 2002 08:46:28 -0700
From: andrew.rich@bigpond.com (Andrew Rich)
Subject: PERL Socket Woes
Message-Id: <73d60405.0210020746.6dd9df95@posting.google.com>

Wondering if someone can give me a hand,

+ Returns connection refused.
+ Netstat on the receiver shows no port 3000 listening.
+ What am I up against ?

#!/usr/bin/perl -w
use strict;
use IO::Socket;
my $sock = IO::Socket::INET-> new(
LocalAddr => 'localhost',
LocalPort => 3000,
Proto => 'tcp',
Listen => 1,
Reuse => 1,
);
die "$!" unless $sock;
my $client;
while ( $client = $sock->accept())
{
print $_;
}
close ($sock);


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

Date: 02 Oct 2002 11:02:21 -0500
From: Joe Halpin <jhalpin@nortelnetworks.com_.nospam>
Subject: Re: PERL Socket Woes
Message-Id: <yxs7k7l0n81e.fsf@nortelnetworks.com_.nospam>

andrew.rich@bigpond.com (Andrew Rich) writes:

> Wondering if someone can give me a hand,
> 
> + Returns connection refused.
> + Netstat on the receiver shows no port 3000 listening.
> + What am I up against ?
> 
> #!/usr/bin/perl -w
> use strict;
> use IO::Socket;
> my $sock = IO::Socket::INET-> new(
> LocalAddr => 'localhost',
> LocalPort => 3000,
> Proto => 'tcp',
> Listen => 1,
> Reuse => 1,
> );
> die "$!" unless $sock;
> my $client;
> while ( $client = $sock->accept())
> {
> print $_;
> }
> close ($sock);

I don't get that on my machine. It opens the listening socket ok, and
I can telnet to the port. When I connect the server prints "Use of
uninitialized value in print at ./test.pl line 15.", which I suppose
is to be expected.

$ perl -version

This is perl, v5.6.0 built for i386-linux

 ...


Joe


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

Date: Wed, 2 Oct 2002 19:26:08 +0200
From: "Dan Borlovan" <danb@mail.dnttm.ro>
Subject: Re: PERL Socket Woes
Message-Id: <anf6n1$6mh$1@nebula.dnttm.ro>

> + Returns connection refused.
> + Netstat on the receiver shows no port 3000 listening.
> LocalAddr => 'localhost',

You are binding to the loopback interface (127.0.0.1), instead of an
interface address?

Dan



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

Date: 02 Oct 2002 17:49:59 +0100
From: Brian McCauley <nobull@mail.com>
Subject: Re: PERL Socket Woes
Message-Id: <u9d6qsokeg.fsf@wcl-l.bham.ac.uk>

andrew.rich@bigpond.com (Andrew Rich) writes:

> Wondering if someone can give me a hand,
> 
> + Returns connection refused.
> + Netstat on the receiver shows no port 3000 listening.
> + What am I up against ?

Dunno.  Your script works fine for me on Linux (I changed 'print $_'
to 'print "wibble\n"' because $_ is empty so it's kinda hard to see
the effect of it being printed). 

BTW: Not that this has anything to do with Perl, but did you really
want to only accept connections on the IPv4 loopback device?

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


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

Date: 02 Oct 2002 13:56:02 GMT
From: vek@pharmnl.ohout.pharmapartners.nl (Villy Kruse)
Subject: Re: reading Cobol PIC 9(6)V99 formats...
Message-Id: <slrnapluni.j3q.vek@pharmnl.ohout.pharmapartners.nl>

On Wed, 02 Oct 2002 10:25:47 +0200,
    Janek Schleicher <bigj@kamelfreund.de> wrote:


>Villy Kruse wrote at Wed, 02 Oct 2002 10:01:31 +0200:
>
>> Just be aware that COBOL is about the only widely used language which
>> supports fixed point decimal numbers.  
>
>As we are in Perl newsgroup we should mention the CPAN module
>Math::FixedPrecision
>


Extremely good ida.



Villy


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

Date: Wed, 02 Oct 2002 08:56:21 -0500
From: Cameron Dorey <camerond@mail.uca.edu>
Subject: Re: Script stops working when DBI added. Why?
Message-Id: <3D9AFB05.6000108@mail.uca.edu>

ColdCathoid wrote:

> Slowly I am getting my brain wrapped around perl. I wrote a CGI script to
> upload files, rename with a unique name and store them on the server. This
> all worked fine and dandy until I decided I wanted to add some database
> functionality with it. I want to connect to a database and store the
> filename and some other related info. But when I add "use DBI" the program
> breaks and I get:
> 
> "Internal Server Error
> The server encountered an internal error or misconfiguration and was unable
> to complete your request.


Since you are using CGI.pm, run your script from a command prompt to see 
the error. It jumps right out at you.

Hint: This script (as copied and pasted to the NG) doesn't work just by 
taking out "use DBI;" you did more to it that you forgot about, or 
didn't send the whole thing.

Cameron

-- 
Cameron Dorey
Associate Professor of Chemistry
University of Central Arkansas
Phone: 501-450-5938
camerond@mail.uca.edu



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

Date: Wed, 2 Oct 2002 08:37:00 -0600
From: "ColdCathoid" <me@me.com>
Subject: Re: Script stops working when DBI added. Why?
Message-Id: <anf0dh$dm0ms$1@ID-158028.news.dfncis.de>


"Cameron Dorey" <camerond@mail.uca.edu> wrote in message
news:3D9AFB05.6000108@mail.uca.edu...
> ColdCathoid wrote:
>
<snip>
>
> Since you are using CGI.pm, run your script from a command prompt to see
> the error. It jumps right out at you.
>
> Hint: This script (as copied and pasted to the NG) doesn't work just by
> taking out "use DBI;" you did more to it that you forgot about, or
> didn't send the whole thing.
>
Actually the script does run fine now. It turns out the editor I was using
at home (when the problems) is different then the one I use at work. For
some reason it added some extra code. When I opened it in trusty Textpad I
deleted those lines and it worked fine.

I double checked what I put in the original post and couldn't see a
difference. But it's early and I haven't had my first coffee yet. =)

I am not able to run it from a command prompt. The hosting company I am with
doesn't allow Unix logins for security reasons. Oh well. Thanks for the
response though.




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

Date: Wed, 02 Oct 2002 15:51:40 GMT
From: helgi@decode.is (Helgi Briem)
Subject: Re: Script stops working when DBI added. Why?
Message-Id: <3d9b14db.2013682432@news.cis.dfn.de>

On Wed, 2 Oct 2002 08:37:00 -0600, "ColdCathoid" <me@me.com>
wrote:
>Actually the script does run fine now. It turns out the editor I was using
>at home (when the problems) is different then the one I use at work. For
>some reason it added some extra code. When I opened it in trusty Textpad I
>deleted those lines and it worked fine.

You probably had Windows linebreaks (\r\n) and the
server in question is Unix and wants plain \n linebreaks.
Upload Perl scripts in ASCII mode.  Most proper editors
you can set to work in either mode.

>I am not able to run it from a command prompt. 

Then set up a web server and Perl on your workstation and
test it there before uploading. Easy enough.

>The hosting company I am with doesn't allow Unix logins for 
>security reasons. 

Not a good reason.  Not a good hosting company.
Consider getting a new one.
-- 
Regards, Helgi Briem
helgi AT decode DOT is

                           A: Top posting
                           Q: What is the most irritating thing on Usenet?
                                           - "Gordon" on apihna


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

Date: Wed, 2 Oct 2002 10:07:20 -0600
From: "ColdCathoid" <me@me.com>
Subject: Re: Script stops working when DBI added. Why?
Message-Id: <anf5mt$dn8k5$1@ID-158028.news.dfncis.de>


"Helgi Briem" <helgi@decode.is> wrote in message
news:3d9b14db.2013682432@news.cis.dfn.de...
> On Wed, 2 Oct 2002 08:37:00 -0600, "ColdCathoid" <me@me.com>
> wrote:
> >Actually the script does run fine now. It turns out the editor I was
using
> >at home (when the problems) is different then the one I use at work. For
> >some reason it added some extra code. When I opened it in trusty Textpad
I
> >deleted those lines and it worked fine.
>
> You probably had Windows linebreaks (\r\n) and the
> server in question is Unix and wants plain \n linebreaks.
> Upload Perl scripts in ASCII mode.  Most proper editors
> you can set to work in either mode.

Yeah I think that was part of the problem as well. I always double check
that that it uploads as ASCII.

> >I am not able to run it from a command prompt.
>
> Then set up a web server and Perl on your workstation and
> test it there before uploading. Easy enough.

Well, no it's not that easy. At work I am limited as to what I can install
on my workstation.

> >The hosting company I am with doesn't allow Unix logins for
> >security reasons.
>
> Not a good reason.  Not a good hosting company.
> Consider getting a new one.

Well, yeah it is a good reason. It met all the requirments that my partner
and I needed. Not being able to login is a minor thing.

Thanks for your thoughts though.




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

Date: Wed, 2 Oct 2002 11:53:18 -0500
From: "William Alexander Segraves" <wsegrave@mindspring.com>
Subject: Re: Script stops working when DBI added. Why?
Message-Id: <anf89h$hin$1@nntp9.atl.mindspring.net>

"ColdCathoid" <me@me.com> wrote in message
news:anf5mt$dn8k5$1@ID-158028.news.dfncis.de...
>
> "Helgi Briem" <helgi@decode.is> wrote in message
> news:3d9b14db.2013682432@news.cis.dfn.de...
> > On Wed, 2 Oct 2002 08:37:00 -0600, "ColdCathoid" <me@me.com>
> > wrote:
<snip>
> >
> > Then set up a web server and Perl on your workstation and
> > test it there before uploading. Easy enough.
>
> Well, no it's not that easy. At work I am limited as to what I can install
> on my workstation.
>

Really? WADR, it appears you are arguing too strongly for your limitations,
instead of seeking a way to overcome them.

It appears you are running Windows at both locations. Why not download and
install IndigoPerl, available free from www.indigostar.org. You'd then have
a local test environment, where you'd be able to debug your scripts before
uploading to your ISP.

Cheers.

Bill Segraves




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

Date: Wed, 2 Oct 2002 11:17:15 -0600
From: "ColdCathoid" <me@me.com>
Subject: Re: Script stops working when DBI added. Why?
Message-Id: <anf9q2$d3001$1@ID-158028.news.dfncis.de>


"William Alexander Segraves" <wsegrave@mindspring.com> wrote in message
news:anf89h$hin$1@nntp9.atl.mindspring.net...
> "ColdCathoid" <me@me.com> wrote in message
> news:anf5mt$dn8k5$1@ID-158028.news.dfncis.de...
> >
> > "Helgi Briem" <helgi@decode.is> wrote in message
> > news:3d9b14db.2013682432@news.cis.dfn.de...
> > > On Wed, 2 Oct 2002 08:37:00 -0600, "ColdCathoid" <me@me.com>
> > > wrote:
> <snip>
> > >
> > > Then set up a web server and Perl on your workstation and
> > > test it there before uploading. Easy enough.
> >
> > Well, no it's not that easy. At work I am limited as to what I can
install
> > on my workstation.
> >
>
> Really? WADR, it appears you are arguing too strongly for your
limitations,
> instead of seeking a way to overcome them.
>
> It appears you are running Windows at both locations. Why not download and
> install IndigoPerl, available free from www.indigostar.org. You'd then
have
> a local test environment, where you'd be able to debug your scripts before
> uploading to your ISP.

Yes I suppose I am. I did not intend to come off as strong as I did and I do
apoligise. It's just some people make generaliztions without knowing my
situation.

You are correct, I am running Windows both at home and at work. I am in the
process of setting up a linux server at home. Hopefully soon I will have
perl running there. But until then I must work with the situation I am
given. I will check out IndigoPerl for sure! BTW it seems to be
www.indigostar.com =) Thank you very much for a very helpful response.




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

Date: Wed, 02 Oct 2002 15:26:10 GMT
From: "Smileface" <smileface@libero.it>
Subject: Sort hash of hash
Message-Id: <meEm9.40089$e31.879070@twister2.libero.it>

Hi,
How can I sort an Hash of Hash by the final values?

The hash is like this:

  %HoH= (
                  'GGG' => { 'd' => 5 },
                  'AAA' => { 'a' => 8 },
                  'ZZZ' => { 'c' => 7 },
                  'DDD' => { 'b' => 6 },
                  'FFF' => { 'e' => 9 }
     );

Thanks in advance,

Smileface




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

Date: Wed, 2 Oct 2002 09:40:58 -0700
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: Sort hash of hash
Message-Id: <3d9b219a$1@news.microsoft.com>

Smileface wrote:
> Hi,
> How can I sort an Hash of Hash by the final values?

That is impossible.
From 'perldoc -q sort':
  How do I sort a hash (optionally by value instead of key)?
            Internally, hashes are stored in a way that prevents you from
            imposing an order on key-value pairs. [...]

Of course you could extract the keys or values or the values of the
dereferenced values (that's probably what you want to look into) into an
array and then sort that. For details please see 'perldoc -q sort':
  How do I sort an array by (anything)?

There is also an module Tie:IxHash or similar (don't nail me on the name)
that reportedly allows a sorted view of a hash. Never used it myself.

jue

jue




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

Date: 02 Oct 2002 15:59:38 GMT
From: ctcgag@hotmail.com
Subject: Re: Speed optimization (with code)
Message-Id: <20021002115938.260$I5@newsreader.com>

Da Witch <heather710101@yahoo.com> wrote:
> I originally posted the post quoted below, but many respondents said
> that they could not comment without seeing a description of the
> algorithm and/or the code.  Here I post both.

This kind of optimization is pretty boring, something people get
paid to do.  So you probably wouldn't get a lot of specific answers
from people here.

> >Is there any other repository of speed optimization ideas for Perl?
> >What tools are good for profiling Perl code?  I've used SmallProf, but
> >it gives me strange results.  (For example, one of the lines that it
> >lists as taking up the most time is something like "my $a = 1e-06;"
> >which is executed only once during the whole program!)

I profiled your code with SmallProf and I do not get anything like that.
Can you post the SmallProf output for the relevant section of your
code?  You could use DProf, but you'd have to break main down into
reasonable subroutines (which you should do anyway).


>
> If a > (ab*ac/tot), then (formally) P is the sum obtained from the
> loop (in pseudocode):
>
>   sum = 0
>   while(a <= top)
>     sum = sum + ab!*cd!*ac!*bd!/(a!*b!*c!*d!*tot!)
>     a = a+1
>     d = d+1
>     b = b-1
>     c = c-1
>   end

What is this?  Is it some kind of Fisher's exact test?



SmallProf showed that the code below is the dominant time sink.


>     for (@nameslist[1..$#nameslist]) {
>       ++$cume;
>       if ($state != $adj->{$_}) {
>         $subtallies[$i++] = $cume;
>         $cume = 0;
>         $state = !$state;
>       }
>     }

I didn't know if I believed that, because the output did look
a little screwy (CPU time was much greater than clock time,
the claimed runtime of these lines was much greater than the total
non-profiling runtime of the program).

So I tested it.  normal runtime was 37 seconds.  If I put a 'next;' right
after the loop, runtime was 25 seconds.  If I put a 'next;' right before
the loop, runtime 1 second.  So 2/3 of the program's time is indeed being
spent in this loop.  Unless you make this loop much faster or do away with
it entirely, nothing else matters much.

The premature 'next' or 'return' is a very powerful profiling tool.
(You do have to be careful that your test are always done with the same
exogenous load on the system.)  Often, running with a profiler
will slow a program 10x, so I can do 5 or so strategically place
short-circuits in the time it would have taken to do 1 profile, and I trust
the results more.


Xho

p.s. caching the slice @nameslist[1..$#nameslist]  will get you ~15%
faster.

-- 
-------------------- http://NewsReader.Com/ --------------------
                    Usenet Newsgroup Service


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

Date: Wed, 02 Oct 2002 12:49:41 GMT
From: stanng@adsl-63-194-216-124.dsl.snfc21.pacbell.net (Stan Ng)
Subject: String substitution of 3+ digit numbers only?
Message-Id: <slrnaplqr0.s9v.stanng@localhost.localdomain>

I need to do a string replacement for numbers with 3 or more digits:

    "Message 345245: Please give 27 dollars to Alice345 at 12:20"

to become

    "Message 3 4 5 2 4 5: Please give 27 dollars to Alice 3 4 5 at 12:20"

That is, numbers more than 2 digits long are blasted apart, but 2-digit
numbers are kept intact.

I need to do this in a single regexp substitution like

   str =~ s/{regexp1}/{regexp2}/g;

or perhaps several substutions. What can I use as regexp1 and regexp2 to 
get this to happen?


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

Date: Wed, 2 Oct 2002 13:22:56 +0000 (UTC)
From: Bernard El-Hagin <bernard.el-hagin@DODGE_THISlido-tech.net>
Subject: Re: String substitution of 3+ digit numbers only?
Message-Id: <slrnaplsmn.1bi.bernard.el-hagin@gdndev25.lido-tech>

In article <slrnaplqr0.s9v.stanng@localhost.localdomain>, Stan Ng wrote:
> I need to do a string replacement for numbers with 3 or more digits:
> 
>     "Message 345245: Please give 27 dollars to Alice345 at 12:20"
> 
> to become
> 
>     "Message 3 4 5 2 4 5: Please give 27 dollars to Alice 3 4 5 at 12:20"
> 
> That is, numbers more than 2 digits long are blasted apart, but 2-digit
> numbers are kept intact.
> 
> I need to do this in a single regexp substitution like
> 
>    str =~ s/{regexp1}/{regexp2}/g;
> 
> or perhaps several substutions. What can I use as regexp1 and regexp2 to 
> get this to happen?


--------
$_ = 'Message 345245: Please give 27 dollars to Alice345 at 12:20';
s#(\d{2}\d+)#join ' ', split //, $1#eg;
--------


Cheers,
Bernard
--
echo 42|perl -pe '$#="Just another Perl hacker,"'


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

Date: Wed, 2 Oct 2002 11:15:42 -0400
From: Jeff 'japhy' Pinyan <pinyaj@rpi.edu>
To: stan_ng@pacbell.net
Subject: Re: String substitution of 3+ digit numbers only?
Message-Id: <Pine.A41.3.96.1021002111400.73930A-100000@cortez.sss.rpi.edu>

On Wed, 2 Oct 2002, Stan Ng wrote:

>I need to do a string replacement for numbers with 3 or more digits:
>
>    "Message 345245: Please give 27 dollars to Alice345 at 12:20"
>
>to become
>
>    "Message 3 4 5 2 4 5: Please give 27 dollars to Alice 3 4 5 at 12:20"
>
>That is, numbers more than 2 digits long are blasted apart, but 2-digit
>numbers are kept intact.

Well, this might be messier than the other solution...

  s/(\d(?=\d\d)|(?<=\d)\d(?=\d))/$1 /g;

but it basically says "if a digit IS FOLLOWED by two more digits, or if a
digit IS PRECEDED AND FOLLOWED by a digit, replace it with itself followed
by a space.

Thus, "1" stays "1", "12" stays "12", "123" becomes "1 2 3", and "1234"
becomes "1 2 3 4".

-- 
Jeff "japhy" Pinyan      RPI Acacia Brother #734      2002 Acacia Senior Dean
"And I vos head of Gestapo for ten     | Michael Palin (as Heinrich Bimmler)
 years.  Ah!  Five years!  Nein!  No!  | in: The North Minehead Bye-Election
 Oh.  Was NOT head of Gestapo AT ALL!" | (Monty Python's Flying Circus)



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

Date: Wed, 02 Oct 2002 13:08:28 GMT
From: Joel Wiesen <Wiesen@personnelselection.com>
Subject: Tab function not working w IE
Message-Id: <3D9AEFCD.6DFE6362@personnelselection.com>

I am using PERL to send email and am having a formatting problem.

The tab function \t works fine when received by Netscape but seems to be
ignored by Internet Explorer.

What do you suggest?  (I would prefer not to send HTML emails, since not
everyone reads them.)

Thanks.

Joel


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

Date: Wed, 2 Oct 2002 15:30:57 +0200
From: "Alan J. Flavell" <flavell@mail.cern.ch>
Subject: Re: Tab function not working w IE
Message-Id: <Pine.LNX.4.40.0210021517180.11776-100000@lxplus076.cern.ch>

On Oct 2, Joel Wiesen inscribed on the eternal scroll:

> I am using PERL to send email

I'm using coffee to help me write software.  Does that make my
software development problems on-topic for rec.food.drink.coffee, or
my choice of blend on-topic for c.l.p.misc?

> and am having a formatting problem.

mmm...

> The tab function \t works fine when received by Netscape but seems to be
> ignored by Internet Explorer.

The tab character is a tab character irrespective of which programming
language you use for generating, you know.  If you're aware that there
are clients which don't behave sensibly in response to \t, then how
about not using it?  Its effect isn't exactly standardised.

> What do you suggest?

That you don't have a Perl language problem.

What is it that you're _really_ troubled by - is it that you're
worried about some folks using proportional fonts, and not getting
columns lined-up properly?  I'm afraid that's a fact of life when
viewing plain text - your readers will have to learn to cope with it,
there's very little you can do in plain text that'll help, other than
to suggest they should choose a monospaced font.

But if you want to discuss the details, I'd recommend finding a group
which discusses Microsoft mail clients.  They might know a workaround
for the tab problem, which you could then recommend to your readers.

[f'ups suggested - feel free to make a better choice]



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

Date: Wed, 02 Oct 2002 14:07:50 GMT
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Tab function not working w IE
Message-Id: <slrnaplvam.2p8.tadmc@magna.augustmail.com>

Joel Wiesen <Wiesen@personnelselection.com> wrote:

> I am using PERL to send email and am having a formatting problem.


If you were using Java or Visual Basic, you would have the same problem.

Your question is not related to the programming language that
generated tabs in its output, it is related to how tabs are
handled in a particular browser.

In short, your problem is not a Perl problem, it is a browser problem.


> The tab function 


tab is not a function, it is a character.


> \t works fine when received by Netscape but seems to be
> ignored by Internet Explorer.
> 
> What do you suggest?  


Asking in a newsgroup about browsers, such as:

      comp.infosystems.www.browsers.ms-windows


> (I would prefer not to send HTML emails, since not
> everyone reads them.)


A voice of sanity in a generally insane world.

Very refreshing.  :-)


> Thanks.


You're welcome.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: Wed, 02 Oct 2002 18:00:04 GMT
From: Alex Robinson <alex_perl@tranzoa.com>
Subject: Re: Two email things in Perl
Message-Id: <3D9B3421.3D04@tranzoa.com>

Adam Knowles wrote:
> .. What am I doing wrong?  I suspect it's cuz my prog thinks STDIN has
> finished after it gets two new lines (after the 'From' line that it
> correctly writes to file). Best way around this?  Do I have to use
> MIME::Lite and stuff?

An extra note that's not been mentioned yet: if you're under Win/DOS,
then you must be able to handle emails with Control Z's in them. Control
Z is an end-of-text file indicator. Call:

    binmode(FILE_HANDLE);

right after the open(). Calling binmode() on STDIN can leave you in a
bad state, though. You'll need to get it back out of binary mode,
probably.

 ... which gets to the reason it's generally easier to read emails from
email files rather than from STDIN.  And, to do that, you may want:


	use     Mail::Util qw( read_mbox );    
	my @mail = read_mbox($file_name);

This reads a "standard" Unix mailbox file. It doesn't work properly on
Netscape files, which are extremely similar. If you have Netscape files,
ping me off line. I've code to handle them.

Hope this helps.

Alex


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

Date: 2 Oct 2002 06:34:32 -0700
From: caligari2k@yahoo.com (James)
Subject: Re: Why are the columns of a MySQL SELECT scrambled?
Message-Id: <3b25bd38.0210020534.70add784@posting.google.com>

I want to thank everyone who responded.  The unordered hash is
obviously the problem I am having.  A few of the suggestions gave me
ideas, especially the multiple arrays.  Which isn't a bad idea
considering what I am wanting to ultimately do.  Again, the key was to
write code that isn't aware of the column names so that it can be more
generic (ie reusable with little modification).  I'm just used to
looping through hashes is all and this is the first time where the
order was important.  :-)

So thank you all.

James

caligari2k@yahoo.com (James) wrote in message news:<3b25bd38.0210011406.cecb586@posting.google.com>...
> This is an interesting situation I have.  I have something like:
> 
>     $myquery = "SELECT * FROM main where centernumber = ?";
>     $sth = $dbh->prepare($myquery);
>     $sth->execute(2);
> 
> Now, I know I only have 1 row that is being returned, but due to the
> nature of the code I'm trying to write (ie very very generic) I return
> the row via the following:
> 
>     my $row = $sth->fetchrow_hashref;
> 
> Then I can parse the hash to get the column names plus the value of
> said column associated with centernumber=2.  Here's the kicker, the
> hash is all scrambled.  If I use the command line client for mysql and
> execute the same query, it is ordered like I want it.  But not here! 
> I can see this by using
> 
>     print Dumper($row);
> 
> So when I loop through the the columnnames, everything is out of
> whack.  So is there a way to tell the DBI or something so that the
> columns are returned in the order they are set in the database? 
> phpMyAdmin seems to do OK at returning the correct column order.
> 
> What I'm doing is taking the data in the database and comparing it to
> the data just submitted via a web page.  That's right, not the other
> way around, because not all paramenters are necessarily passed by the
> webpage and I am validating the database data.  So I know the database
> has all the parameter names, ie columns.
> 
> If there is a problem, then I can output appropriate HTML.  I am open
> to all sorts of suggestions, but as I said, I'm trying to keep this
> totally generic.  In other words, the code doesn't have a clue about
> the structure of the database, the parameters on the webpage, etc, and
> so far I've done pretty good job of it.  I'm just up against the wall
> right now because I want the discrepancies displayed in the same order
> they were entered.  Which of course matches the order of the database.
> 
> Confused yet?  Good, so am I!  I'm stumped!  Either that, or my brain
> just finally decided to quit telling me the answers!  :-)
> 
> Thanks
> 
> James


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

Date: Wed, 02 Oct 2002 15:04:21 GMT
From: Bart Lateur <bart.lateur@pandora.be>
Subject: Re: Why are the columns of a MySQL SELECT scrambled?
Message-Id: <r82mpu04tmkdn3iq406ptr9l0ph1653gfo@4ax.com>

James wrote:

>This is an interesting situation I have.  I have something like:
>
>    $myquery = "SELECT * FROM main where centernumber = ?";
>    $sth = $dbh->prepare($myquery);
>    $sth->execute(2);
>
>Now, I know I only have 1 row that is being returned, but due to the
>nature of the code I'm trying to write (ie very very generic) I return
>the row via the following:
>
>    my $row = $sth->fetchrow_hashref;

As you probably know by now, if you care about the field ordering, don't
rely on a hash.

Instead, you can use fetchrow_array:

>    my @row = $sth->fetchrow_array;

The ordering of the field values (no names)  in this array will be the
same as MySQL returned them. No names. For the names, use:

	my @fieldname = @{$sth->{NAME}};

You'll get $fieldname[3] as the field name with $row[3] as a value, for
example. To get them all, use some sort of loop with an array index
going from 0 to $#row === $#fieldname.

You have to do this after you did $sth->execute(...), but not
necessarily before or after doing $sth->fetchrow_array.

Oh, and if you're retrieving only one row, please do

	$sth->finish;

before destroying $sth.

-- 
	Bart.


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

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


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