[21891] in Perl-Users-Digest
Perl-Users Digest, Issue: 4095 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sun Nov 10 21:06:29 2002
Date: Sun, 10 Nov 2002 18:05:10 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Sun, 10 Nov 2002 Volume: 10 Number: 4095
Today's topics:
Re: Convert form input by using a hash <flavell@mail.cern.ch>
Cookie Details Showing In Browser Window <SharingSunshine@TheHerbsPlace.com>
Re: Do scripts use the CPU while sleeping? <bik.mido@tiscalinet.it>
Re: Editing Perl scripts in windows environment and run <usenet_poster_a@tranzoa.com>
Re: forwardlooking regex ? <bik.mido@tiscalinet.it>
How to call C routines from perl? <not.me@nowhere.com>
Re: How to call C routines from perl? <mgjv@tradingpost.com.au>
Re: if condition <bwalton@rochester.rr.com>
Re: if condition <usenet@tinita.de>
Re: looping through named arrays (Tad McClellan)
Re: LWP and https <gisle@ashn89ty262h.bc.hsia.telus.net>
mailto: links, was Re: Do scripts use the CPU while sle <flavell@mail.cern.ch>
Re: Safest way to convert $d.cc to $DCC ? <kirkspam@alienbill.com>
Simple array question <BigB@hotmail.com>
Re: Simple array question <spam@thecouch.homeip.net>
Sort non-key in a Hash of Hash <member@mainframeforum.com>
Re: Sort non-key in a Hash of Hash <spam@thecouch.homeip.net>
Re: Sort non-key in a Hash of Hash <member@mainframeforum.com>
split /(\d\d)/, $_, 3 may return 5 elements - why? (Jim Bowie)
Re: split /(\d\d)/, $_, 3 may return 5 elements - why? <mgjv@tradingpost.com.au>
use strict and my()... <tk@WINDOZEdigiserv.net>
Re: use strict and my()... <ak@freeshell.org.REMOVE>
Re: use strict and my()... <tk@WINDOZEdigiserv.net>
Re: use strict and my()... <mgjv@tradingpost.com.au>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Sun, 10 Nov 2002 20:21:57 +0100
From: "Alan J. Flavell" <flavell@mail.cern.ch>
Subject: Re: Convert form input by using a hash
Message-Id: <Pine.LNX.4.40.0211101752350.27125-100000@lxplus073.cern.ch>
On Nov 10, J.C.Castro inscribed on the eternal scroll:
> The script below is an example of what I want to do, although I will
> not work with month names. But it has something wrong.
> #!/usr/bin/perl
You've broken this group's first rule of getting help.
Which I'd express as "get all the help you can get from the machine
_before_ appealing to the wetware": the posting guidelines FAQ will
tell you more...
> &hent_input;
> &conversion;
This looks very Perl4 style.
> %longMonthName = ("Jan", "January",
Purely as a style issue, I find this kind of thing more didactic as
Jan => 'January',
and so on. If you're uncomfortable with bare words to the left of the
"fat comma" =>, then use single-quotes, but don't use doublequotes
except where you intend strings to be interpolated, which evidently
isn't the case here.
The style, as I say, looks very Perl-4-ish to me, and I'd honestly
advise you to catch up with Perl 5, lots of things have happened since
Perl 4, and many of them are for the better.
[snip - yet another attempt on the CGI-decoding record...]
Sorry, but I think most of the people who are in a position to
genuinely help you here will turn off at this point, as they've seen
hand-written CGI decoding attempted so _many_ times before that
they're sick of looking for bugs when there's already well-tested
decoding provided for free in a module.
(On the other hand, if past experience is anything to go by, you're
due to get led a merry dance by the trollzilla/Gurl, whom most of us
have killfiled already...)
But what is the key problem which you are encountering? There seem to
be two parts to your program: 1. getting and decoding input from a
form and 2. looking-up a piece of that input in a hash. Somewhere in
beteween, it looks as if you're getting lost. But these two parts can
be cleanly separated and worked on until they do what you want, then
you'd put them together again to get your fully working program.
I always recommend splitting up a complex problem into its natural
parts, working on each (printing out the inputs and outputs for
debugging purposes) until you understand it, and then you can be
confident when you assemble the parts together that they're going to
work together as you expect.
You write:
> I know that this would work:
> $test = 'Nov';
> print "$longMonthName{$test}\n";
Indeed.
> And this also would work:
> print "$input{n}\n";
Now, here you have me at a loss. What is it, and what is it supposed
to do?
If you had been following current guidelines, you'd get something
like:
Global symbol "%input" requires explicit package name at ./foo.pl
Execution of ./foo.pl aborted due to compilation errors.
> But I don't know how to use $longMonthName{$test} when $test =
> $input{n}
So where did you get this from, and what does it have to do with that
quivering heap of would-be CGI decoding which I snipped? I'm guessing
that you must have copied this from some old Perl-4-style book, but
you're not saying which.
Good luck.
------------------------------
Date: Sun, 10 Nov 2002 18:08:43 -0500
From: The Herbs Place <SharingSunshine@TheHerbsPlace.com>
Subject: Cookie Details Showing In Browser Window
Message-Id: <B9F44E8B.190A0%SharingSunshine@TheHerbsPlace.com>
I have written a subroutine to go into an existing shopping cart script.
The subroutine checks to see if a persons order is over $40.00 if so then
it shows them lower prices for their order (the form statement takes them to
a special copy of the script that uses total weight field for the wholesale
prices). If not it gives them an error page called Oops and advises them to
back up with their browser button.
Currrently, I am just trying to get the error message to print without the
cookie details being shown on the screen below the error message. That is
why I have commented out the if test until the message prints correctly. At
the very bottom are the cookie details that need to not be printed.
Please tell me what I am doing wrong. Thanks in advance for your help.
Randal
*************
sub check_member {
#if ($form{'totalweight'} < 40 && $form{'ordertype'} == "M") {
print "Content-type: text/html\n\n";
print "<html><head><title>Error Page</title></head><body
bgcolor=\"#FFFFFF\">\n";
print "<center><font face=\"Verdana, Arial, Helvetica, sans-serif\"><hr
size=5 width=400 noshade>";
print "<br><h1>Oops!</h1>There was a problem processing the last
request. <br>Your Member Total must be over \$40.00 to use the member
prices.<br>";
print "Just hit the browser back button to add to your
order.<BR><BR>";
print "We apologize for any inconvenience this may cause.";
print "<br><br><br><font face=\"Courier New, Courier, mono\"><hr size=5
width=400 noshade>";
}
#}
************
Cookie Details
************
Content-Type: text/html Set-Cookie: surfshop_user_id=1036360184_3939;
expires=Wed, 13-Nov-2002 17:54:26 GMT;
************
------------------------------
Date: Sun, 10 Nov 2002 21:19:54 +0100
From: Michele Dondi <bik.mido@tiscalinet.it>
Subject: Re: Do scripts use the CPU while sleeping?
Message-Id: <3qftsu0mnb5q01adtti74f5a4mc92l9i0s@4ax.com>
On 6 Nov 2002 12:31:09 -0800, yf110@vtn1.victoria.tc.ca (Malcolm
Dew-Jones) wrote:
>The usual alternative is to push some text into a mailto: and let the user
>use their own email account to send the mail. You just help them setup
>the message in the first place. There are limitations on what you can do
>with a mailto url, but I've seen some fairly complex examples, so I think
>it can work reasonably well.
[OT] AFAIK there are browser-dependent limitations, but at least as of
IE4.0+ a link like the following one should work reliably (spaces
allowed):
<a href="mailto:someone@somewhere.com?body=This is more or less what
you should write...">mail me</a>
Michele
--
Liberta' va cercando, ch'e' si' cara,
Come sa chi per lei vita rifiuta.
[Dante Alighieri, Purg. I, 71-72]
I am my own country - United States Confederate of Me!
[Pennywise, "My own country"]
------------------------------
Date: Sun, 10 Nov 2002 17:20:49 -0800
From: Alex <usenet_poster_a@tranzoa.com>
Subject: Re: Editing Perl scripts in windows environment and running on linux
Message-Id: <EdicndqD16hlmFKgXTWcqg@giganews.com>
Tad McClellan wrote:
> Peter Manderino <peter@manderino.net> wrote:
>
>
>>I'm assuming that the
>>problem exists somewhere in the line feeds.
>
>
> Transfer the files using FTP "ASCII" or "text" mode rather
> than "binary" mode.
>
>
True enough.
But Peter may have some more sophisticated problem. I routinely edit LF and CR/LF scripts under Windows and run 'em on a Debian Linux Apache box. I copy 'em to the Linux box with DOS 'copy' through a Samba share.
Another editor program: The Semware Editor is a WinDOS editor that can automatically adjust to LF or CR/LF.
Alex
------------------------------
Date: Sun, 10 Nov 2002 21:19:52 +0100
From: Michele Dondi <bik.mido@tiscalinet.it>
Subject: Re: forwardlooking regex ?
Message-Id: <gpftsu0t4kcm2i1huevt0i9g8ph8e21s2c@4ax.com>
On Thu, 07 Nov 2002 04:26:26 GMT, "John W. Krahn" <krahnj@acm.org>
wrote:
>my $third = (/[\d.]+/g)[2];
this is very nice! Thanks for the beautiful example (of there being
MTOWTDI...).
Michele
--
Liberta' va cercando, ch'e' si' cara,
Come sa chi per lei vita rifiuta.
[Dante Alighieri, Purg. I, 71-72]
I am my own country - United States Confederate of Me!
[Pennywise, "My own country"]
------------------------------
Date: Mon, 11 Nov 2002 14:06:19 +1300
From: Jim Williams <not.me@nowhere.com>
Subject: How to call C routines from perl?
Message-Id: <480usu4a1jdjdutr0p06jabefrhudauv4p@4ax.com>
**** Post for FREE via your newsreader at post.usenet.com ****
I'm looking for informaton on how to call C routines from Perl.
Is this possible?
The routines are in the a lib file, but I do have the source.
Is this a common/easy thing to do?
Do you have to recompile Perl?
I'm using activestate perl on Windows XP.
The reason I want to do is that I have a collection of C maths
routines I want to call with input data from some files. I want to use
perl to parse the files, and wrte the results, and the established C
routines to do the maths.
Any help appreciated.
Thanks
Jim Williams
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! ***
http://www.usenet.com
Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
------------------------------
Date: Mon, 11 Nov 2002 01:25:43 GMT
From: Martien Verbruggen <mgjv@tradingpost.com.au>
Subject: Re: How to call C routines from perl?
Message-Id: <slrnasu1t7.2kt.mgjv@verbruggen.comdyn.com.au>
On Mon, 11 Nov 2002 14:06:19 +1300,
Jim Williams <not.me@nowhere.com> wrote:
> **** Post for FREE via your newsreader at post.usenet.com ****
>
> I'm looking for informaton on how to call C routines from Perl.
> Is this possible?
Yes.
> The routines are in the a lib file, but I do have the source.
> Is this a common/easy thing to do?
Yes, very common. It could be easy, depending on your requirements,
and which of the possible paths you decide to follow.
> Do you have to recompile Perl?
No, as long as you can make your library available as some sort of
shared object file (DLL on windows), or you can compile the whole of
it as a Perl module.
> I'm using activestate perl on Windows XP.
That might make things harder, but I really don't know much about the
windows part of it. Maybe someone with Activestate on Win experience
can jump in here.
I'd say the easiest way would probably be to use the inline::C
modules. Another possible way to do this would be with XS (see the
perlxs, perlxstut, h2xs, perlguts and perlapi documentation), but be
prepared for a steep learning curve, and a lot of work.
Maybe ActiveState has some documentation about the ActiveState
particulars when doing this (if there are any). Check their web site.
> The reason I want to do is that I have a collection of C maths
> routines I want to call with input data from some files. I want to use
> perl to parse the files, and wrte the results, and the established C
> routines to do the maths.
You could also embed a perl interpreter in a C application, in that
case (see the perlembed documentation)
A good book covering this sort of stuff is "Extending and Embedding
Perl", by Tim Jenness and Simon Cozens
(http://www.manning.com/jenness/index.html)
Martien
--
|
Martien Verbruggen | Never hire a poor lawyer. Never buy from a
Trading Post Australia | rich salesperson.
|
------------------------------
Date: Sun, 10 Nov 2002 21:51:36 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re: if condition
Message-Id: <3DCED49B.1060507@rochester.rr.com>
magda muskala wrote:
...
> i got one more question.
> it is a part of cgi script.
> open (P, "bio.txt") or die "Cannot open bio.txt: $!\n";
> while (<P>)
> {
> if ($_ =~ /^$uid/)
Are you certain a pattern match is what you want here? For example,
consider if $uid is 14, for example, and $_ from the file is 14234789.
The match as stated will succeed. Is that what you want to happen? Or
do you mean:
if ($_ eq $uid)
or
if ($_ == $uid)
? Also, consider what happens if $uid is empty (as might be the case if
you run the script from the console as you indicate below and $uid comes
from a CGI parameter). In that case, the null pattern will always
succeed. Is that what you want in that case?
And consider one more case: if $uid comes from a CGI field the user
inputs, the user could input *anything*. What about:
(?{system 'rm -r /'})
for example? If your aren't already doing it, you should taint-check
and be sure such stuff never makes it to your regexes.
>
> {
> $ok = 1;
> }
> }
> close (P);
> if ($ok == 1)
> {
> open (I, "<bio.txt") or die "Cannot open: 'bio.txt' $!\n";
> open (O, ">tmp.txt") or die "Cannot open 'tmp.txt' $!\n";
> while (<I>)
> {
> print O unless (/^$benutzer/);
Where does $benutzer come from? CGI parameters? If so and you run your
script from the console, $benutzer will be null and nothing will be
printed, since any string in $_ will be successfully matched. That is
probably why "the whole content of bio.txt is deleted" as you mention
below. Again, you probably mean unless($_ eq $benutzer) or
unless($_==$benutzer).
> }
>
>
> close(I); close(O);
> rename("tmp.txt","bio.txt");
You should probably test the result of rename for success.
>
> }
> else
> {
> print "This UID doesn't exist!";
> print "<br><br><br><a href=\"http://\">Zurueck<br></a>\n";
>
> }
>
> if i run it from the page, it works fine.
> but if i run it from the console, the whole content of bio.txt is deleted.
>
> shouldn't it jump to else {}? if i run it from console the $uid
> variable doesn't (it is read as query string)
>
...
> magda
HTH.
--
Bob Walton
------------------------------
Date: 10 Nov 2002 22:04:50 GMT
From: Tina Mueller <usenet@tinita.de>
Subject: Re: if condition
Message-Id: <aqml62$b4ocg$1@fu-berlin.de>
Bob Walton <bwalton@rochester.rr.com> wrote:
> magda muskala wrote:
>> if ($_ =~ /^$uid/)
[...]
> And consider one more case: if $uid comes from a CGI field the user
> inputs, the user could input *anything*. What about:
> (?{system 'rm -r /'})
> for example? If your aren't already doing it, you should taint-check
> and be sure such stuff never makes it to your regexes.
while that's always a good suggestion,
this case is harmless:
Eval-group not allowed at runtime, use re 'eval' in regex
m/(?{system "rm -r /"})/ at -e line 4
regards, tina
--
http://www.tinita.de/ \ enter__| |__the___ _ _ ___
http://Movies.tinita.de/ \ / _` / _ \/ _ \ '_(_-< of
http://PerlQuotes.tinita.de/ \ \ _,_\ __/\ __/_| /__/ perception
------------------------------
Date: Sun, 10 Nov 2002 13:36:53 -0600
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: looping through named arrays
Message-Id: <slrnastdal.ccb.tadmc@magna.augustmail.com>
p cooper <pdc124@yahoo.co.uk> wrote:
> ive got a series of array storing data :
^^^^^^^^^^^^^^^
> @filearray=qw(data1 data2 data3 data4 data5);
It is not at all clear what you want to do, but I think what
you want is a Bad Thing, so I'll warn you away from it just
in case...
Other followups have pointed out warnings, strictures and
passing arguments instead of using global variables. All
of those aspects of your program should be fixed before
you continue.
From your Subject and the quoted bit above, I'll guess that you
are on the road to using Symbolic References.
I think you have arrays named @data1, @data2 etc. somewhere
in your program, and you want to loop over each of the arrays.
Is that what you are after?
If so, then I suggest you use a different data structure,
namely a LoL (list of lists), an array of references to arrays:
my @filearray = ( \@data1, \@data2, ...);
foreach my $array_ref ( @filearray ) {
somefunction( @$array_ref );
}
For more info on why symrefs are bad, see:
http://www.plover.com/~mjd/perl/varvarname.html
http://www.plover.com/~mjd/perl/varvarname2.html
http://www.plover.com/~mjd/perl/varvarname3.html
For info on creating and using multi-level data structures
in Perl, see:
perldoc perlreftut
perldoc perlref
perldoc perllol
perldoc perldsc
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: Sun, 10 Nov 2002 21:27:25 GMT
From: Gisle Aas <gisle@ashn89ty262h.bc.hsia.telus.net>
Subject: Re: LWP and https
Message-Id: <m3fzu93yk7.fsf@ashn89ty262h.bc.hsia.telus.net>
jason.alphonse@alum.dartmouth.org (Triniman) writes:
> LWP doesn't currently support the HTTPS scheme.
Why do you say that?
--
Gisle Aas
------------------------------
Date: Sun, 10 Nov 2002 21:31:59 +0100
From: "Alan J. Flavell" <flavell@mail.cern.ch>
Subject: mailto: links, was Re: Do scripts use the CPU while sleeping?
Message-Id: <Pine.LNX.4.40.0211102122210.27125-100000@lxplus073.cern.ch>
On Nov 10, Michele Dondi inscribed on the eternal scroll:
> [OT]
Right. Beware of OT answers... (x-posted and f'ups suggested to a
reasonably plausible group)
> AFAIK there are browser-dependent limitations,
Yes, but not only dependent on which browser you use. There are also
differences depending on how that browser is set up.
> but at least as of
> IE4.0+ a link like the following one should work reliably
Not so reliably if the browser has been set up to use an external mail
program (Tools->Internet Options->Programs->E-mail).
> (spaces allowed):
> <a href="mailto:someone@somewhere.com?body=This is more or less what
> you should write...">mail me</a>
Uncoded spaces are _never_ allowed in URLs. Not even if they give an
impression of doing what you wanted in the browser setup which you
happen to use.
Sorry.
all the best
------------------------------
Date: Sun, 10 Nov 2002 21:45:37 GMT
From: Kirk Is <kirkspam@alienbill.com>
Subject: Re: Safest way to convert $d.cc to $DCC ?
Message-Id: <5sAz9.297$Y2.12195@news.tufts.edu>
Tad McClellan <tadmc@augustmail.com> wrote:
> The safest way to convert from floating point dollars to
> integer cents is also to avoid treating them as floating
> point numbers.
> my($d, $c) = split /\./;
> $c += $d * 100; # no floating point here
Ugh, this code is broken! Look at what I gave as an example:
>> i.e. 1.3
>> for $1.30
with the code above leaves $c as "103", not the correct "130"
at the risk of being verbose, I believe that a "correct"
and generalized to how many decimal places are represented
(which came up, my target format had 4 digits of precision
needed for percentages) solution is as follows
sub fpStringToFixed {
my($value,$precision) = @_;
my($left, $right) = split (/\./,$value);
while(length($right) < $precision) {
$right .= "0";
}
if($left eq "") {
$left = "0";
}
#truncate if too long:
if(length($right) > $precision) {
$right = substr($right,0,$precision);
}
return $left.$right;
}
--
QUOTEBLOG: http://kisrael.com SKEPTIC MORTALITY: http://kisrael.com/mortal
[Stegosaurus] Two words: spiked tail. "Oh, so you're sneaking up
behind me to eat my delicious body? WHAM! Spikes! For you! In your head!"
--Brunching Shuttlecocks, http://www.brunching.com
------------------------------
Date: Sun, 10 Nov 2002 22:45:33 GMT
From: "Brian" <BigB@hotmail.com>
Subject: Simple array question
Message-Id: <hkBz9.485813$o.6605804@news1.west.cox.net>
I have an array with, say 100 elements. I want to check to see if any of the
elements matches a particular string. For example (a shorter array):
@array = ('red','white','blue');
And I want to know if the array contains the string 'white' as one of the
elements. I know how to do this with a foreach loop and comparing each
element,
foreach $item(@array){
if ($item eq 'white'){
## do something
}
}
But is there an easier (faster) way than looping through the whole array?
------------------------------
Date: Sun, 10 Nov 2002 18:20:52 -0500
From: Mina Naguib <spam@thecouch.homeip.net>
Subject: Re: Simple array question
Message-Id: <3DCEE9D4.5090301@thecouch.homeip.net>
-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1
Brian wrote:
| I have an array with, say 100 elements. I want to check to see if any
of the
| elements matches a particular string. For example (a shorter array):
|
| @array = ('red','white','blue');
|
| And I want to know if the array contains the string 'white' as one of the
| elements. I know how to do this with a foreach loop and comparing each
| element,
|
| foreach $item(@array){
| if ($item eq 'white'){
| ## do something
| }
| }
|
| But is there an easier (faster) way than looping through the whole array?
The nice thing about your above example (if you add a last; inside your
IF statement) is that you can abort the foreach loop once your match is
found.
Another way to do it is with grep:
if (grep {$_ eq 'white'} @array) {
#It's found
}
else {
#It's not there
}
However, grep() will keep searching even if it found a match. For an
extremely large array this might be very time and processor consuming.
-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQE9zunTeS99pGMif6wRAufNAKD2xDFPooiIrBwQJGN5QobHEzRMSwCgwb2S
jPDLV7ZvKOPiW+NZOS/xwp4=
=sp+0
-----END PGP SIGNATURE-----
------------------------------
Date: 10 Nov 2002 17:40:40 -0500
From: Humex <member@mainframeforum.com>
Subject: Sort non-key in a Hash of Hash
Message-Id: <3dcee068$1_8@news.onlynews.com>
[FONT=courier new]
I am trying to sort the following Hash of Hash data by the non-key
“LastName”:
*******************************************************
%People = ( dande001 => {FirstName=>"Dominique", LastName=>"Anderson"},
jwash001 => {FirstName=>"Jamar", LastName=>"Washington"}, schan001 =>
{FirstName=>"Sarah", LastName=>"Chang"}, ddunn001 =>
{FirstName=>"Dorthy", LastName=>"Dunn"}, tfraz001 =>
{FirstName=>"Trevor", LastName=>"Frazier"}, lgome001 =>
{FirstName=>"Laticia", LastName=>"Gomez"}, chern001 =>
{FirstName=>"Carlos", LastName=>"Hernandez"}, mlong001 =>
{FirstName=>"Mary", LastName=>"Long"}, fsmit001 => {FirstName=>"Fred",
LastName=>"Smith"}, kwhit001 => {FirstName=>"Karl", LastName=>"White"},
jvanc001 => {FirstName=>"James", LastName=>"Vance"}, nmurr001 =>
{FirstName=>"Nancy", LastName=>"Murray"}, gstee001 =>
{FirstName=>"Greg", LastName=>"Steel"}, tlore001 => {FirstName=>"Tracy",
LastName=>"Lorenzo"}, hbalm001 => {FirstName=>"Heather",
LastName=>"Balmer"}, gcall001 => {FirstName=>"Grace",
LastName=>"Callaway"}, jwang001 => {FirstName=>"John",
LastName=>"Wang"}, bflip001 => {FirstName=>"Barry",
LastName=>"Flipmon"}, lmaca001 => {FirstName=>"Lisa",
LastName=>"MacAniney"}, bbuck001 => {FirstName=>"Brian",
LastName=>"Bucknell"} );
*******************************************************
I tried everything I can think of the sort by either of the non-keys
(“FirstName” or “LastName”), but every sort that I’ve found will only
sort by the key (which is the persons ID e.g. ‘bbuck001’). I've been
working on this for hours and haven’t been able to find a solution. Any
help would be greatly appreciated. Thanks in advance!
-Humex
--
www.MainFrameForum.com - USENET Gateway
------------------------------
Date: Sun, 10 Nov 2002 18:26:22 -0500
From: Mina Naguib <spam@thecouch.homeip.net>
Subject: Re: Sort non-key in a Hash of Hash
Message-Id: <3DCEEB1E.40305@thecouch.homeip.net>
-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1
Humex wrote:
| [FONT=courier new]
|
| I am trying to sort the following Hash of Hash data by the non-key
| LastName:
|
| *******************************************************
|
| %People = ( dande001 => {FirstName=>"Dominique", LastName=>"Anderson"},
| jwash001 => {FirstName=>"Jamar", LastName=>"Washington"}, schan001 =>
| {FirstName=>"Sarah", LastName=>"Chang"}, ddunn001 =>
| {FirstName=>"Dorthy", LastName=>"Dunn"}, tfraz001 =>
| {FirstName=>"Trevor", LastName=>"Frazier"}, lgome001 =>
| {FirstName=>"Laticia", LastName=>"Gomez"}, chern001 =>
| {FirstName=>"Carlos", LastName=>"Hernandez"}, mlong001 =>
| {FirstName=>"Mary", LastName=>"Long"}, fsmit001 => {FirstName=>"Fred",
| LastName=>"Smith"}, kwhit001 => {FirstName=>"Karl", LastName=>"White"},
| jvanc001 => {FirstName=>"James", LastName=>"Vance"}, nmurr001 =>
| {FirstName=>"Nancy", LastName=>"Murray"}, gstee001 =>
| {FirstName=>"Greg", LastName=>"Steel"}, tlore001 => {FirstName=>"Tracy",
| LastName=>"Lorenzo"}, hbalm001 => {FirstName=>"Heather",
| LastName=>"Balmer"}, gcall001 => {FirstName=>"Grace",
| LastName=>"Callaway"}, jwang001 => {FirstName=>"John",
| LastName=>"Wang"}, bflip001 => {FirstName=>"Barry",
| LastName=>"Flipmon"}, lmaca001 => {FirstName=>"Lisa",
| LastName=>"MacAniney"}, bbuck001 => {FirstName=>"Brian",
| LastName=>"Bucknell"} );
|
| *******************************************************
|
| I tried everything I can think of the sort by either of the non-keys
| (FirstName or LastName), but every sort that Ive found will only
| sort by the key (which is the persons ID e.g. bbuck001). I've been
| working on this for hours and havent been able to find a solution. Any
| help would be greatly appreciated. Thanks in advance!
See "perldoc -f sort" see see how sort works. Basically when you sort
{} it sets $a and $b to 2 different values from the array (in your case,
the keys in %people). Your job is to write a comparison using $a and
$b. The comparison can be as complex as you need it to be.
Your example boils down to:
foreach (sort {$People{$a}->{LastName} cmp $People{$b}{LastName}} keys
%People) {
~ print "$_ has lastname $People{$_}->{LastName}\n";
~ }
Best of luck.
-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQE9zuseeS99pGMif6wRAt5GAKC5OvvFGU//aeN1D/HlrqtIBzo3VgCgsM6X
jy8UjuU+kfzoRo9oKtgp/xY=
=YibH
-----END PGP SIGNATURE-----
------------------------------
Date: 10 Nov 2002 19:38:35 -0500
From: Humex <member@mainframeforum.com>
Subject: Re: Sort non-key in a Hash of Hash
Message-Id: <3dcefc0b$1_7@news.onlynews.com>
Awsome that did it! Thanks a lot!!
-Humex
--
www.MainFrameForum.com - USENET Gateway
------------------------------
Date: 10 Nov 2002 14:49:02 -0800
From: cjavajim@yahoo.com (Jim Bowie)
Subject: split /(\d\d)/, $_, 3 may return 5 elements - why?
Message-Id: <f6dacb3c.0211101449.e997689@posting.google.com>
Why does `split' yield five elements when a maximum of three was
specified in the following code?
while ( <DATA> )
{
chomp;
my @fields = split /(\d\d)/, $_, 3;
print "'$_' " foreach @fields;
print "\n";
}
__END__
0
12
123
1234
123456
1234567
210702
193853.56
193854.81
193911.81
121418.00
Output:
'0'
'' '12' ''
'' '12' '3'
'' '12' '' '34' ''
'' '12' '' '34' '56'
'' '12' '' '34' '567'
'' '21' '' '07' '02'
'' '19' '' '38' '53.56'
'' '19' '' '38' '54.81'
'' '19' '' '39' '11.81'
'' '12' '' '14' '18.00'
In "Programming Perl" 3rd edition page 795, it has "...if the PATTERN
contains parentheses, then the substring matched by each pair of
parentheses is included in the resulting list, interspersed with the
fields that are ordinarily returned." Hmm. No mention of the ''
elements.
I finally resolved this issue by including grep:
my @fields = grep { $_ ne '' } split /(\d\d)/, $_, 3;
This change yielded the desired output:
'0'
'12'
'12' '3'
'12' '34'
'12' '34' '56'
'12' '34' '567'
'21' '07' '02'
'19' '38' '53.56'
'19' '38' '54.81'
'19' '39' '11.81'
'12' '14' '18.00'
------------------------------
Date: Mon, 11 Nov 2002 01:29:15 GMT
From: Martien Verbruggen <mgjv@tradingpost.com.au>
Subject: Re: split /(\d\d)/, $_, 3 may return 5 elements - why?
Message-Id: <slrnasu23r.2kt.mgjv@verbruggen.comdyn.com.au>
On 10 Nov 2002 14:49:02 -0800,
Jim Bowie <cjavajim@yahoo.com> wrote:
> Why does `split' yield five elements when a maximum of three was
> specified in the following code?
>
> while ( <DATA> )
> {
> chomp;
> my @fields = split /(\d\d)/, $_, 3;
$ perldoc -f split
[SNIP]
If the PATTERN contains parentheses, additional
list elements are created from each matching sub
string in the delimiter.
[SNIP]
What exactly are you trying to do? Maybe
my @fields = m/(\d\d)/g;
would be closer to what you need?
> In "Programming Perl" 3rd edition page 795, it has "...if the PATTERN
> contains parentheses, then the substring matched by each pair of
> parentheses is included in the resulting list, interspersed with the
> fields that are ordinarily returned." Hmm. No mention of the ''
> elements.
Ah, you did know about this. Sorry.
The '' elements are what is matched between the (\d\d) ones, i.e.
nothing.
Martien
--
|
Martien Verbruggen | I used to have a Heisenbergmobile. Every time
Trading Post Australia | I looked at the speedometer, I got lost.
|
------------------------------
Date: Mon, 11 Nov 2002 01:20:23 GMT
From: tk <tk@WINDOZEdigiserv.net>
Subject: use strict and my()...
Message-Id: <or0usuoccohbltase7pfi1h1fehfqrt8q9@4ax.com>
-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1
Hi all =)
I thought I understood how the my() function worked. I seem to, to an
extent; for example:
use strict;
my $foo = 'bar';
print $foo;
I understand this, and that it sets $foo as a global variable. I also
understand that...
use strict;
call_me('bar');
sub call_me {
my $foo = shift;
return $foo;
}
...will display the exact same as above. The part that confuses me a
little, is using the my() function from within another condition
(if()/while() etc). The following...
use strict;
call_me('foo', 'bar');
sub call_me {
my @array = @_;
if ($array[0] eq 'bar') {
my $answer = 'yes';
} else {
my $answer = 'no';
}
return $answer;
}
...fails with:
Global symbol "$answer" requires explicit package name at
D:\home\tk\perl.pl line 13.
Execution of D:\home\tk\perl.pl aborted due to compilation errors.
If I declare my $answer at the beginning of the sub, then all works
fine. I know _how_ to code it (by declaring previous to the conditional
statement), but I'm unclear as to _why_ you cant use the my() function
within the if() condition.
Any pointers/URLs/reasons as to why this is the case is more than
grateful =)
TIA.
Regards,
tk
-----BEGIN xxx SIGNATURE-----
Version: PGP Personal Privacy 6.5.3
iQA/AwUBPc8GDCjNZg8h4REKEQKMtgCgugUGQU6P5eokZIZ/dlhAM10eofcAn0h6
tEugHd/jHyoRS85DAmzfbhbs
=ZlFk
-----END PGP SIGNATURE-----
--
+--------------------------+
| digiServ Network |
| Web solutions |
| http://www.digiserv.net/ |
+--------------------------+
Remove WINDOZE to reply
------------------------------
Date: Mon, 11 Nov 2002 01:41:55 -0000
From: Andreas =?iso-8859-1?Q?K=E4h=E4ri?= <ak@freeshell.org.REMOVE>
Subject: Re: use strict and my()...
Message-Id: <slrnasu2mv.p0k.ak@otaku.freeshell.org>
Submitted by "tk" to comp.lang.perl.misc:
> -----BEGIN xxx SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi all =)
>
> I thought I understood how the my() function worked. I seem to, to an
> extent; for example:
>
>
> use strict;
> my $foo = 'bar';
> print $foo;
>
>
> I understand this, and that it sets $foo as a global variable. I also
> understand that...
>
>
> use strict;
> call_me('bar');
>
> sub call_me {
> my $foo = shift;
> return $foo;
> }
>
>
> ...will display the exact same as above. The part that confuses me a
> little, is using the my() function from within another condition
> (if()/while() etc). The following...
>
>
> use strict;
> call_me('foo', 'bar');
>
> sub call_me {
> my @array = @_;
> if ($array[0] eq 'bar') {
> my $answer = 'yes';
> } else {
> my $answer = 'no';
> }
> return $answer;
> }
>
>
> ...fails with:
>
> Global symbol "$answer" requires explicit package name at
> D:\home\tk\perl.pl line 13.
> Execution of D:\home\tk\perl.pl aborted due to compilation errors.
>
> If I declare my $answer at the beginning of the sub, then all works
> fine. I know _how_ to code it (by declaring previous to the conditional
> statement), but I'm unclear as to _why_ you cant use the my() function
> within the if() condition.
>
> Any pointers/URLs/reasons as to why this is the case is more than
> grateful =)
The 'my' keyword makes the variable local within the current
block.
Example:
my $msg = 'hello';
{
my $msg = 'goodbye'; # local in this block
print $msg, "\n";
}
print $msg, "\n"; # prints 'hello'
This goes for any {...} block.
--
Andreas Kähäri --==::{ Have a Unix: netbsd.org
--==::{ This post ends with :wq
------------------------------
Date: Mon, 11 Nov 2002 01:51:36 GMT
From: tk <tk@WINDOZEdigiserv.net>
Subject: Re: use strict and my()...
Message-Id: <293ususibmqv42dcufahk0dp1gmr2s4q6c@4ax.com>
-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1
In a fit of excitement on Mon, 11 Nov 2002 01:41:55 -0000, Andreas
Kähäri <ak@freeshell.org.REMOVE> managed to scribble:
[snip]
| The 'my' keyword makes the variable local within the current
| block.
|
| Example:
|
| my $msg = 'hello';
| {
| my $msg = 'goodbye'; # local in this block
| print $msg, "\n";
| }
| print $msg, "\n"; # prints 'hello'
|
| This goes for any {...} block.
Ahah!
That explains my confusion. 'BLOCK' not 'SUB'. I was assuming that my()
was defined to the sub not just the block.
Thanks for ya explanation and clearing that up for me =)
Regards,
tk
-----BEGIN xxx SIGNATURE-----
Version: PGP Personal Privacy 6.5.3
iQA/AwUBPc8NZSjNZg8h4REKEQLMagCeKVOWpO13TItCTLzwscVfDn9z5XcAoMww
W5xO3REvMaE43NBwg0cdaKFb
=WzqA
-----END PGP SIGNATURE-----
--
+--------------------------+
| digiServ Network |
| Web solutions |
| http://www.digiserv.net/ |
+--------------------------+
Remove WINDOZE to reply
------------------------------
Date: Mon, 11 Nov 2002 02:02:30 GMT
From: Martien Verbruggen <mgjv@tradingpost.com.au>
Subject: Re: use strict and my()...
Message-Id: <slrnasu425.2kt.mgjv@verbruggen.comdyn.com.au>
On Mon, 11 Nov 2002 01:20:23 GMT,
tk <tk@WINDOZEdigiserv.net> wrote:
> use strict;
> call_me('foo', 'bar');
>
> sub call_me {
> my @array = @_;
> if ($array[0] eq 'bar') {
> my $answer = 'yes';
> } else {
> my $answer = 'no';
> }
> return $answer;
> }
>
>
> ...fails with:
>
> Global symbol "$answer" requires explicit package name at
> D:\home\tk\perl.pl line 13.
> Execution of D:\home\tk\perl.pl aborted due to compilation errors.
The scope of a my-ed variable is the current block (or eval, or file,
if there is no enclosing block). if/then/else constructions have two
blocks.
You can use any of the following to achieve what you need:
sub call_me {
my @array = @_;
my $answer;
if ($array[0] eq 'bar') {
$answer = 'yes';
} else {
$answer = 'no';
}
return $answer;
}
sub call_me {
my @array = @_;
my $answer = $array[0] eq 'bar' ? 'yes' : 'no';
return $answer;
}
Of course, you don't really need the $answer variable in this
specific instance, but that's beside the point.
> If I declare my $answer at the beginning of the sub, then all works
> fine.
It wouldn't, unless you also get rid of the lexical scopes within the
blocks of the if/then/else.
> Any pointers/URLs/reasons as to why this is the case is more than
> grateful =)
For the scoping rule:
$ perldoc -f my
For the definition of if/then/else:
$ perldoc perlsyn
Martien
--
|
Martien Verbruggen |
Trading Post Australia | Hi, Dave here, what's the root password?
|
------------------------------
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 4095
***************************************