[28437] in Perl-Users-Digest
Perl-Users Digest, Issue: 9801 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Oct 4 03:06:08 2006
Date: Wed, 4 Oct 2006 00:05:06 -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, 4 Oct 2006 Volume: 10 Number: 9801
Today's topics:
Re: FAQ 5.2 <uri@stemsystems.com>
Re: FAQ 5.2 <nospam-abuse@ilyaz.org>
Need hep with printing a file uing Win32::Printer <imfeaw5672@pacbell.net>
new CPAN modules on Wed Oct 4 2006 (Randal Schwartz)
Re: Perl Async .10 <toddenglish@gmail.com>
Re: Perl Async .10 <toddenglish@gmail.com>
Re: Perl Async .10 <DJStunks@gmail.com>
Re: Perl Async .10 <kkeller-usenet@wombat.san-francisco.ca.us>
Re: perl flawed or my fault <nospam-abuse@ilyaz.org>
Re: Reducing dependencies when initializing Log4perl? (reading news)
Re: Spliting values and reversing a hash <attn.steven.kuo@gmail.com>
Re: Spliting values and reversing a hash mlwollman@gmail.com
Re: Spliting values and reversing a hash <someone@example.com>
Re: Spliting values and reversing a hash (reading news)
Re: Spliting values and reversing a hash <someone@example.com>
Re: Spliting values and reversing a hash <kkeller-usenet@wombat.san-francisco.ca.us>
Re: Spliting values and reversing a hash <attn.steven.kuo@gmail.com>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Tue, 03 Oct 2006 23:37:20 -0400
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: FAQ 5.2
Message-Id: <x7d598iwen.fsf@mail.sysarch.com>
>>>>> "JG" == Jim Gibson <jgibson@mail.arc.nasa.gov> writes:
>>
>> my $text ; { local $/ ; $text = <> }
anyhow that would be simpler as:
my $text = do { local $/ ; <> }
JG> Not that one; the idea is to get the lines into an array and modify the
JG> array. Putting the entire file into a single scalar would be another
JG> example, but I don't know if we need another one.
JG> It looks like I used the term "slurp" incorrectly, as the Camel book
JG> defines it as reading the entire file into a string, not an array.
i say slurping is anytime you read in a whole file at a time, regardless
of putting it into a scalar or array of lines.
uri
--
Uri Guttman ------ uri@stemsystems.com -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org
------------------------------
Date: Wed, 4 Oct 2006 05:53:08 +0000 (UTC)
From: Ilya Zakharevich <nospam-abuse@ilyaz.org>
Subject: Re: FAQ 5.2
Message-Id: <efvi84$pf7$1@agate.berkeley.edu>
[A complimentary Cc of this posting was NOT [per weedlist] sent to
Dr.Ruud
<rvtol+news@isolution.nl>], who wrote in article <efv2vh.1d0.1@news.isolution.nl>:
> Jim Gibson schreef:
>
> > You can "slurp" one or more files into an array, modify the array,
> > and write the array out to a new file, specifying the file(s) on the
> > command-line:
> >
> > @lines = do { local $/; <> }
>
> ITYM:
>
> @lines = <> ;
>
> or:
>
> my $text ; { local $/ ; $text = <> }
For this semantic, I would prefer the combination
my $text = do { local $/; <> };
Although in FAQ, the priorities are somewhat different than in real life...
Hope this helps,
Ilya
------------------------------
Date: Wed, 04 Oct 2006 05:04:48 GMT
From: "sm" <imfeaw5672@pacbell.net>
Subject: Need hep with printing a file uing Win32::Printer
Message-Id: <QhHUg.8784$vJ2.6755@newssvr12.news.prodigy.com>
Hi Folks,
I do not know if this is the right place for this. I am writing a "Perl TK
script that runs on windows and
have been trying to print add a *print* capability to for the UI. I have
found *Win32::Printer*, *Win32::Printer::Direct*
I have attempted:
1- to get the user selected *printer name* from the *Win32::Printer* to
use in *Win32::Printer::Direct*
In this attempt, I have not found a way of getting the *printer
name* form *Win32::Printer* after user
selects a printer.
2- I can not find a way of get the selected file name or file handle to
*Win32::Printer*
I my attempts have been based on the sample code provided in the pod.
Any help is greatly appreciated.
Best regards,
-sm
------------------------------
Date: Wed, 4 Oct 2006 04:42:09 GMT
From: merlyn@stonehenge.com (Randal Schwartz)
Subject: new CPAN modules on Wed Oct 4 2006
Message-Id: <J6LH29.uFA@zorch.sf-bay.org>
The following modules have recently been added to or updated in the
Comprehensive Perl Archive Network (CPAN). You can install them using the
instructions in the 'perlmodinstall' page included with your Perl
distribution.
AI-MegaHAL-0.04_01
http://search.cpan.org/~chorny/AI-MegaHAL-0.04_01/
Perl interface to the MegaHAL natural language conversation simulator.
----
Alien-wxWidgets-0.22
http://search.cpan.org/~mbarbon/Alien-wxWidgets-0.22/
building, finding and using wxWidgets binaries
----
Business-IBAN-0.06
http://search.cpan.org/~tinita/Business-IBAN-0.06/
Validate and generate IBANs
----
CGI-Application-Plugin-Output-XSV-0.9
http://search.cpan.org/~zackse/CGI-Application-Plugin-Output-XSV-0.9/
generate csv output from a CGI::Application runmode
----
CPAN-1.88_52
http://search.cpan.org/~andk/CPAN-1.88_52/
query, download and build perl modules from CPAN sites
----
Catalyst-View-HTML-Embperl-0.01
http://search.cpan.org/~alet/Catalyst-View-HTML-Embperl-0.01/
HTML::Embperl View Class
----
Data-FormValidator-4.49_1
http://search.cpan.org/~markstos/Data-FormValidator-4.49_1/
Validates user input (usually from an HTML form) based on input profile.
----
Devel-EvalContext-0.05
http://search.cpan.org/~bsmith/Devel-EvalContext-0.05/
Perl extension for blah blah blah
----
Error-0.17005
http://search.cpan.org/~shlomif/Error-0.17005/
Error/exception handling in an OO-ish way
----
FLV-Info-0.15
http://search.cpan.org/~clotho/FLV-Info-0.15/
Extract metadata from Macromedia Flash Video files
----
File-BOM-0.13
http://search.cpan.org/~mattlaw/File-BOM-0.13/
Utilities for handling Byte Order Marks
----
HTML-Selector-XPath-0.02
http://search.cpan.org/~miyagawa/HTML-Selector-XPath-0.02/
CSS Selector to XPath compiler
----
InSilicoSpectro-Databanks-0.0.13
http://search.cpan.org/~alexmass/InSilicoSpectro-Databanks-0.0.13/
parsing protein/nucleotides sequence databanks (fasta, uniprot...)
----
InSilicoSpectro-Databanks-0.0.14
http://search.cpan.org/~alexmass/InSilicoSpectro-Databanks-0.0.14/
parsing protein/nucleotides sequence databanks (fasta, uniprot...)
----
Inline-C2XS-0.04
http://search.cpan.org/~sisyphus/Inline-C2XS-0.04/
create an XS file from an Inline C file.
----
LRpt_0.16
http://search.cpan.org/~pkaluski/LRpt_0.16/
Perl extension for comparing and reporting results of database selects
----
Lingua-EN-WSD-CorpusBased-0.11
http://search.cpan.org/~reiter/Lingua-EN-WSD-CorpusBased-0.11/
Word Sense Disambiguation using a domain corpus
----
Net-Appliance-Phrasebook-0.05
http://search.cpan.org/~oliver/Net-Appliance-Phrasebook-0.05/
Network appliance command-line phrasebook
----
Net-Appliance-Session-0.05
http://search.cpan.org/~oliver/Net-Appliance-Session-0.05/
Run command-line sessions to network appliances
----
Object-InsideOut-2.03
http://search.cpan.org/~jdhedden/Object-InsideOut-2.03/
Comprehensive inside-out object support module
----
Object-InsideOut-2.04
http://search.cpan.org/~jdhedden/Object-InsideOut-2.04/
Comprehensive inside-out object support module
----
PAR-0.955
http://search.cpan.org/~smueller/PAR-0.955/
Perl Archive Toolkit
----
PAR-0.956
http://search.cpan.org/~smueller/PAR-0.956/
Perl Archive Toolkit
----
POE-Component-IKC-0.1900
http://search.cpan.org/~gwyn/POE-Component-IKC-0.1900/
POE Inter-Kernel Communication
----
POE-Component-IKC-0.1901
http://search.cpan.org/~gwyn/POE-Component-IKC-0.1901/
POE Inter-Kernel Communication
----
Parallel-Forker-1.211
http://search.cpan.org/~wsnyder/Parallel-Forker-1.211/
Parallel job forking and management
----
Perl-Metrics-Simple-0.012
http://search.cpan.org/~matisse/Perl-Metrics-Simple-0.012/
Count packages, subs, lines, etc. of many files.
----
RDF-Notation3-0.91
http://search.cpan.org/~pcimprich/RDF-Notation3-0.91/
RDF Notation3 parser
----
RT-Client-REST-0.27
http://search.cpan.org/~dmitri/RT-Client-REST-0.27/
talk to RT installation using REST protocol.
----
SystemPerl-1.272
http://search.cpan.org/~wsnyder/SystemPerl-1.272/
SystemPerl Language Extension to SystemC
----
Term-Animation-2.1.1
http://search.cpan.org/~kbaucom/Term-Animation-2.1.1/
ASCII sprite animation framework
----
Test-WWW-Jaunt-0.01_03
http://search.cpan.org/~rkrimen/Test-WWW-Jaunt-0.01_03/
A CGI-based testing platform.
----
WWW-Scraper-ISBN-Siciliano_Driver-0.01
http://search.cpan.org/~joenio/WWW-Scraper-ISBN-Siciliano_Driver-0.01/
Search driver for Siciliano's online catalog.
----
Win32-InstallShield-0.2
http://search.cpan.org/~kbaucom/Win32-InstallShield-0.2/
InstallShield data file interface
----
Wx-Perl-FSHandler-LWP-0.02
http://search.cpan.org/~mbarbon/Wx-Perl-FSHandler-LWP-0.02/
file system handler based upon LWP
----
YAML-Syck-0.71
http://search.cpan.org/~audreyt/YAML-Syck-0.71/
Fast, lightweight YAML loader and dumper
If you're an author of one of these modules, please submit a detailed
announcement to comp.lang.perl.announce, and we'll pass it along.
This message was generated by a Perl program described in my Linux
Magazine column, which can be found on-line (along with more than
200 other freely available past column articles) at
http://www.stonehenge.com/merlyn/LinuxMag/col82.html
print "Just another Perl hacker," # the original
--
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: 3 Oct 2006 18:42:55 -0700
From: "Todd English" <toddenglish@gmail.com>
Subject: Re: Perl Async .10
Message-Id: <1159926175.857729.159020@k70g2000cwa.googlegroups.com>
> I think it's a bug in Async.pm that has to do with buffering.
> Async uses a buffer of size 8192. If you make the output string
> longer than that (printing only a bit of it), all processes will
> return values. If it is much shorter, (half that size or so) gaps
> will start to appear.
>
> Anno
Anno,
I'm not sure I follow you. As a test I returned really really long
messages and I also tried changing the buffer size to in the perl
module to 10. In either case, I still see the same behavior.
I must admit that reading the perl in Async.pm is a little more
advanced than my few days of using perl will allow me to comprehend.
But if I am reading this correctly, the buffer you are talking about is
the child's return data buffer. I put some debug print commands into
that area of the Async module; specifically I printed out the return
value of sysread and value of buf. It turns out the sysread is
returning 0 for many of the calls. I'm now wondering if there is a
problem with the system call getting interrupted and the child ready
loop isn't handling it correctly. I'll look into that tonight.
Thanks for the advice,
-T
------------------------------
Date: 3 Oct 2006 21:48:47 -0700
From: "Todd English" <toddenglish@gmail.com>
Subject: Re: Perl Async .10
Message-Id: <1159937327.082769.322120@e3g2000cwe.googlegroups.com>
> But you will in the present?
Sorry Tad, I misunderstood you.
> Google is not Usenet.
Very astute observation. I use Google to post because it is convenient.
However both my work and home isp's news servers list perl.beginners as
a valid group. I readily accept that yours doesn't and you couldn't
post your TOFU comments to a nonexistent group.
> No, else I would have given one.
>
> I don't have that module installed, and don't have the time to try it.
Well, thank you for taking the time to give me some Usenet etiquette
advice.
-T
------------------------------
Date: 3 Oct 2006 22:00:56 -0700
From: "DJ Stunks" <DJStunks@gmail.com>
Subject: Re: Perl Async .10
Message-Id: <1159938056.454136.326120@m73g2000cwd.googlegroups.com>
Todd English wrote:
> Thank you for the reply.
Please don't snip attributions. That is, don't snip the part that says
what I wrote. Otherwise, who are you thanking?
> > my hunch was that your problem occurred because you're deleting items
> > from the hash while iterating over it, but on second thought I'm not so
> > sure.
>
> I originally thought this as well, and had tried a couple of variants
> to the code I posted where I didn't mess with the proc hash until all
> procs had reported their return. But this didn't make any difference
> and upon further reflection I didn't think this was the case.
>
> > anyway, I changed up your script a bit (no more deleting) and it seems
> > to run ok for me. give it a try.
>
> I tried your example code 10 times on three different machines and I
> don't see any difference between your output and mine. For example I
> just ra the example and received:
> Host gray:
> Host x.x.x.x: x.x.x.x result
> Host y.y.y.y: y.y.y.y result
> Host maroon:
> Host white:
> Host goldenrod:
> Host rh4as:
> Host mambo:
> Host brown:
> Host green: green result
This is the results from the _exact_ script I posted, or did you modify
it somehow?
Did you uncomment those diagnostic prints in
long_running_computation()? Did you see all your processes spawned,
and all of them eventually return?
> I'm wondering if this is environmental. Are you on a windows machine,
> or a UNIX like machine? What version of perl are you using?
That was on win32: Perl v5.8.7; Async v0.10.
-jp
PS - by the way, upon further reflection I decided I would change:
sleep 10 while any{ not $_->{process}->ready() } @hosts;
to
sleep 10 while notall{ $_->{process}->ready() } @hosts;
but that's a style issue (and one less keystrokes to boot) :-)~
------------------------------
Date: Tue, 3 Oct 2006 22:20:52 -0700
From: Keith Keller <kkeller-usenet@wombat.san-francisco.ca.us>
Subject: Re: Perl Async .10
Message-Id: <busbv3x6q8.ln2@goaway.wombat.san-francisco.ca.us>
["Followup-To:" header set to comp.lang.perl.misc.]
On 2006-10-04, Todd English <toddenglish@gmail.com> wrote:
[> Tad McClellan wrote:]
Please don't snip attributions!
> Very astute observation. I use Google to post because it is convenient.
> However both my work and home isp's news servers list perl.beginners as
> a valid group. I readily accept that yours doesn't and you couldn't
> post your TOFU comments to a nonexistent group.
Did you read the rest of Tad's comments about perl.beginners? It's
a mailing list gated to usenet, not a real newsgroup. Often posts
to those pseudogroups get sent to the bitbucket, either by your
own newsserver or by the mailing list in question. If you look at the
real archive (at http://www.nntp.perl.org/group/perl.beginners/) you'll
see your posts are not there. (Why Google groups misleadingly shows
them is beyond me.) If you want an answer from there, subscribe to the
mailing list.
It seems like you're making progress with your problem here, so if
you haven't read the Posting Guidelines, drop perl.beginners, and good
luck resolving the issue.
--keith
--
kkeller-usenet@wombat.san-francisco.ca.us
(try just my userid to email me)
AOLSFAQ=http://www.therockgarden.ca/aolsfaq.txt
see X- headers for PGP signature information
------------------------------
Date: Wed, 4 Oct 2006 05:50:29 +0000 (UTC)
From: Ilya Zakharevich <nospam-abuse@ilyaz.org>
Subject: Re: perl flawed or my fault
Message-Id: <efvi34$p7j$1@agate.berkeley.edu>
[A complimentary Cc of this posting was sent to
John W. Krahn
<krahnj@telus.net>], who wrote in article <SJyUg.49711$E67.23424@clgrps13>:
> > I am of a split mind about using ?: in lvalue context. It *is*
> > kind of obscure, but there are situations that simply call for
> > it. One is the loop of a binary search, for example
> >
> > while ( $low < $high - 1 ) {
> > my $mid = ($low + $high)/2;
> > $list->[ $mid] le $targ ? $low : $high = $mid;
> > }
> > The if-else equivalent to ?: is four lines, even cuddling the else.
> > I can never bring myself to use it.
> I assume that you meant to write:
>
> ( $list->[ $mid] le $targ ? $low : $high ) = $mid;
>
> because your example never assigns a value to $low.
This discussion shows my RULE ONE of Perl:
Do not ever try to memorize the relative precedence of operators.
If you religeously follow this advice, then the following RULE TWO
will help you a lot:
If in any doubt, put parentheses.
Myself, I still manage to follow the rule one. I DO NOT know relative
precedence of + vs &, or of = vs &, or of =~ vs =. This is a useless
knowledge with very dear consenquences if you misremember...
What is important to have clean readable text of a program:
while vs or/and;
or/and vs everything else;
the "logical" part of arithetic operations.
All the rest deserves blissfulness. What is (length 8 + 2)?
Hope this helps,
Ilya
------------------------------
Date: Wed, 04 Oct 2006 02:31:10 GMT
From: "Mumia W. (reading news)" <paduille.4058.mumia.w@earthlink.net>
Subject: Re: Reducing dependencies when initializing Log4perl?
Message-Id: <O1FUg.6649$o71.1467@newsread3.news.pas.earthlink.net>
On 10/03/2006 07:20 PM, robb@acm.org wrote:
> Mumia W. (reading news) wrote:
>> package MyLogWrapper;
>> use strict;
>> use warnings;
>> use LogForPerl; # Placeholder for Log::Log4perl
>>
>> BEGIN {
>> LogForPerl->init('/path/to/log.conf');
>> }
>>
>> sub get_logger {
>> LogForPerl->get_logger('MyPackage::MySubPackage');
>> }
>>
>> __END__
>>
>
> But the point is that it should be usable from many packages. And, I
> don't want to have code inside a package which hardcodes the package
> name... So what I'm looking for, I guess, is code to fill this blank:
>
> sub get_logger {
> my $package_name = ... #Code to determine package of caller
> LogForPerl->get_logger($package_name);
> }
>
Use the "caller" function:
sub get_logger {
my $package_name = caller();
LogForPerl->get_logger($package_name);
}
Read "perldoc -f caller"
HTH
--
paduille.4058.mumia.w@earthlink.net
Posting Guidelines for comp.lang.perl.misc:
http://www.augustmail.com/~tadmc/clpmisc/clpmisc_guidelines.html
------------------------------
Date: 3 Oct 2006 18:21:32 -0700
From: "attn.steven.kuo@gmail.com" <attn.steven.kuo@gmail.com>
Subject: Re: Spliting values and reversing a hash
Message-Id: <1159924891.954927.290220@i3g2000cwc.googlegroups.com>
John W. Krahn wrote:
> mlwollman@gmail.com wrote:
> >
> > I'm very, very new to Perl, and I have a question I can't quite find
> > the answer in the O'Reilly Perl books (Learning, Programming, and
> > Cookbook). Any assistance would be helpful.
> >
> > I have a hash with key value pairs like:
> > 1 => Chocolate,Vanilla,Rocky Road
> > 2 => Strawberry,Vanilla, Pistachio
> > 3 => Cookie Dough,Chocolate
> > 4 => Strawberry,Pistachio
> >
> > And I need to transform it to:
> > Chocolate => 1,3
> > Vanilla => 1,2
> > Rocky Road => 1
> > Strawberry => 2,4
> > Pistachio =>2,4
> > Cookie Dough => 3
> >
> > What's a good, simple way to do that?
>
> $ perl -le'
> use Data::Dumper;
>
> my %hash = (
> 1 => [ "Chocolate", "Vanilla", "Rocky Road" ],
> 2 => [ "Strawberry", "Vanilla", "Pistachio" ],
> 3 => [ "Cookie Dough", "Chocolate" ],
> 4 => [ "Strawberry", "Pistachio" ],
> );
>
> print Dumper \%hash;
>
> for my $key ( keys %hash ) {
> for my $flavour ( @{ delete $hash{ $key } } ) {
> push @{ $hash{ $flavour } }, $key;
> }
> }
>
> print Dumper \%hash;
(snipped)
If I recall correctly, it isn't a good idea to delete
and add keys to a hash while iterating over it.
--
Regards,
Steven
------------------------------
Date: 3 Oct 2006 18:37:38 -0700
From: mlwollman@gmail.com
Subject: Re: Spliting values and reversing a hash
Message-Id: <1159925858.425043.135050@c28g2000cwb.googlegroups.com>
Thank You, Bob. That worked perfectly! Much appreciated.
Matt
Bob Walton wrote:
> mlwollman@gmail.com wrote:
> ...
> > I have a hash with key value pairs like:
> > 1 => Chocolate,Vanilla,Rocky Road
> > 2 => Strawberry,Vanilla, Pistachio
> > 3 => Cookie Dough,Chocolate
> > 4 => Strawberry,Pistachio
> >
> > And I need to transform it to:
> > Chocolate => 1,3
> > Vanilla => 1,2
> > Rocky Road => 1
> > Strawberry => 2,4
> > Pistachio =>2,4
> > Cookie Dough => 3
> >
> > What's a good, simple way to do that?
> >
> > I thought about using while each and changing the value to an array and
> > foreach array element make a new has with the array element as a key
> > and the old key join() any existing values, I think. I'm pretty
> > confused now.
> ...
> > Matt
> >
>
> Here is one way, which is pretty much what you described, except I
> elected to use strings rather than arrays since I think you said you
> wanted strings:
>
> use warnings;
> use strict;
> use Data::Dumper;
> my %h; #original hash
> $h{1}='Chocolate,Vanilla,Rocky Road';
> $h{2}='Strawberry,Vanilla,Pistachio';
> $h{3}='Cookie Dough,Chocolate';
> $h{4}='Strawberry,Pistachio';
> my %h1; #flavors hash
> for(sort keys %h){
> my @v=split /,/,$h{$_}; #separate flavors
> for my $v(@v){
> $h1{$v}.="$_,"; #add number to flavor
> }
> }
> for(keys %h1){
> $h1{$_}=~s/,$//; #get rid of trailing commas
> }
> print Dumper(\%h1);
>
> --
> Bob Walton
> Email: http://bwalton.com/cgi-bin/emailbob.pl
------------------------------
Date: Wed, 04 Oct 2006 02:30:45 GMT
From: "John W. Krahn" <someone@example.com>
Subject: Re: Spliting values and reversing a hash
Message-Id: <p1FUg.50038$E67.15083@clgrps13>
attn.steven.kuo@gmail.com wrote:
> John W. Krahn wrote:
>>
>>for my $key ( keys %hash ) {
>> for my $flavour ( @{ delete $hash{ $key } } ) {
>> push @{ $hash{ $flavour } }, $key;
>> }
>> }
>
> If I recall correctly, it isn't a good idea to delete
> and add keys to a hash while iterating over it.
"for my $key ( keys %hash )" creates a list of the hash keys in memory and any
modifications to %hash inside the loop won't affect the contents of that list.
perldoc -f delete
John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall
------------------------------
Date: Wed, 04 Oct 2006 02:31:12 GMT
From: "Mumia W. (reading news)" <paduille.4058.mumia.w@earthlink.net>
Subject: Re: Spliting values and reversing a hash
Message-Id: <Q1FUg.6650$o71.2961@newsread3.news.pas.earthlink.net>
On 10/03/2006 07:18 PM, mlwollman@gmail.com wrote:
> Hello all,
>
> I'm very, very new to Perl, and I have a question I can't quite find
> the answer in the O'Reilly Perl books (Learning, Programming, and
> Cookbook). Any assistance would be helpful.
>
> I have a hash with key value pairs like:
> 1 => Chocolate,Vanilla,Rocky Road
> 2 => Strawberry,Vanilla, Pistachio
> 3 => Cookie Dough,Chocolate
> 4 => Strawberry,Pistachio
>
> And I need to transform it to:
> Chocolate => 1,3
> Vanilla => 1,2
> Rocky Road => 1
> Strawberry => 2,4
> Pistachio =>2,4
> Cookie Dough => 3
>
> What's a good, simple way to do that?
>
> I thought about using while each and changing the value to an array and
> foreach array element make a new has with the array element as a key
> and the old key join() any existing values, I think. I'm pretty
> confused now.
>
> Thank You,
> Matt
>
Iterate over the keys and values and use autovivication to push each key
into an anonymous array in a new hash. You would have to split the
values on commas for this to work right.
--
paduille.4058.mumia.w@earthlink.net
Posting Guidelines for comp.lang.perl.misc:
http://www.augustmail.com/~tadmc/clpmisc/clpmisc_guidelines.html
------------------------------
Date: Wed, 04 Oct 2006 02:33:12 GMT
From: "John W. Krahn" <someone@example.com>
Subject: Re: Spliting values and reversing a hash
Message-Id: <I3FUg.50063$E67.15260@clgrps13>
Bob Walton wrote:
>
> Here is one way, which is pretty much what you described, except I
> elected to use strings rather than arrays since I think you said you
> wanted strings:
>
> use warnings;
> use strict;
> use Data::Dumper;
> my %h; #original hash
> $h{1}='Chocolate,Vanilla,Rocky Road';
> $h{2}='Strawberry,Vanilla,Pistachio';
> $h{3}='Cookie Dough,Chocolate';
> $h{4}='Strawberry,Pistachio';
> my %h1; #flavors hash
> for(sort keys %h){
> my @v=split /,/,$h{$_}; #separate flavors
> for my $v(@v){
> $h1{$v}.="$_,"; #add number to flavor
> }
> }
> for(keys %h1){
> $h1{$_}=~s/,$//; #get rid of trailing commas
> }
> print Dumper(\%h1);
Another way to do it:
$ perl -le'
use Data::Dumper;
my %hash = (
1 => "Chocolate,Vanilla,Rocky Road",
2 => "Strawberry,Vanilla, Pistachio",
3 => "Cookie Dough,Chocolate",
4 => "Strawberry,Pistachio",
);
print Dumper \%hash;
for my $key ( keys %hash ) {
for my $flavour ( split /\s*,\s*/, delete $hash{ $key } ) {
push @{ $hash{ $flavour } }, $key;
}
}
$_ = join ",", @$_ for values %hash;
print Dumper \%hash;
'
$VAR1 = {
'4' => 'Strawberry,Pistachio',
'1' => 'Chocolate,Vanilla,Rocky Road',
'3' => 'Cookie Dough,Chocolate',
'2' => 'Strawberry,Vanilla, Pistachio'
};
$VAR1 = {
'Chocolate' => '1,3',
'Cookie Dough' => '3',
'Strawberry' => '4,2',
'Rocky Road' => '1',
'Pistachio' => '4,2',
'Vanilla' => '1,2'
};
John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall
------------------------------
Date: Tue, 3 Oct 2006 20:23:52 -0700
From: Keith Keller <kkeller-usenet@wombat.san-francisco.ca.us>
Subject: Re: Spliting values and reversing a hash
Message-Id: <83mbv3x798.ln2@goaway.wombat.san-francisco.ca.us>
On 2006-10-04, John W. Krahn <someone@example.com> wrote:
> attn.steven.kuo@gmail.com wrote:
>> John W. Krahn wrote:
>>>
>>>for my $key ( keys %hash ) {
>>> for my $flavour ( @{ delete $hash{ $key } } ) {
>>> push @{ $hash{ $flavour } }, $key;
>>> }
>>> }
>>
>> If I recall correctly, it isn't a good idea to delete
>> and add keys to a hash while iterating over it.
>
> "for my $key ( keys %hash )" creates a list of the hash keys in memory and any
> modifications to %hash inside the loop won't affect the contents of that list.
>
> perldoc -f delete
While the actual for loop is documented in perldoc -f delete, the
creating a new list in memory aspect is more explicitly documented in
perldoc -f keys.
--keith
--
kkeller-usenet@wombat.san-francisco.ca.us
(try just my userid to email me)
AOLSFAQ=http://www.therockgarden.ca/aolsfaq.txt
see X- headers for PGP signature information
------------------------------
Date: 3 Oct 2006 22:16:53 -0700
From: "attn.steven.kuo@gmail.com" <attn.steven.kuo@gmail.com>
Subject: Re: Spliting values and reversing a hash
Message-Id: <1159939013.404809.30580@h48g2000cwc.googlegroups.com>
John W. Krahn wrote:
> attn.steven.kuo@gmail.com wrote:
(snipped)
> >
> > If I recall correctly, it isn't a good idea to delete
> > and add keys to a hash while iterating over it.
>
> "for my $key ( keys %hash )" creates a list of the hash keys in memory and any
> modifications to %hash inside the loop won't affect the contents of that list.
>
> perldoc -f delete
Sorry, my recollection was indeed faulty.
I was thinking of the 'each' function used
to iterate over a hash.
--
Regards,
Steven
------------------------------
Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>
Administrivia:
#The Perl-Users Digest is a retransmission of the USENET newsgroup
#comp.lang.perl.misc. For subscription or unsubscription requests, send
#the single line:
#
# subscribe perl-users
#or:
# unsubscribe perl-users
#
#to almanac@ruby.oce.orst.edu.
NOTE: due to the current flood of worm email banging on ruby, the smtp
server on ruby has been shut off until further notice.
To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.
#To request back copies (available for a week or so), send your request
#to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
#where x is the volume number and y is the issue number.
#For other requests pertaining to the digest, send mail to
#perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
#sending perl questions to the -request address, I don't have time to
#answer them even if I did know the answer.
------------------------------
End of Perl-Users Digest V10 Issue 9801
***************************************