[21991] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4213 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Dec 4 06:05:42 2002

Date: Wed, 4 Dec 2002 03:05:07 -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           Wed, 4 Dec 2002     Volume: 10 Number: 4213

Today's topics:
    Re: [FTP] Downloading a file by matching part of its na <krahnj@acm.org>
    Re: any cool script site??? palladium@spinn.net
    Re: any cool script site??? (Helgi Briem)
    Re: C to perl, very large data files, efficiency, idiom (qanda)
        child signal <lois@hotmail.com>
    Re: child signal <lshaw-usenet@austin.rr.com>
    Re: child signal <tassilo.parseval@post.rwth-aachen.de>
    Re: how to get it quoted? btam01@ccsf.edu
    Re: HTML parse & then get text WITH tags from between t <teacraft@163.com.blah>
        passing data between perl scripts and a module: probabl (benrog)
        PeggyPro IDE/Editor (Paul R.)
    Re: Perl Packages question palladium@spinn.net
        Re FAQ: How can I capture STDERR from an external comma (Peter J. Acklam)
    Re: Regular expressions <linuxnb@yahoo.com>
        Warnings when creating an array of hashes <s.patterson@freeuk.com>
    Re: Warnings when creating an array of hashes <tassilo.parseval@post.rwth-aachen.de>
    Re: Warnings when creating an array of hashes <tassilo.parseval@post.rwth-aachen.de>
        Win32 and *NIX, cryptographically secure random numbers <michael@giantsquidmarks.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Wed, 04 Dec 2002 05:18:06 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: [FTP] Downloading a file by matching part of its name (code incl.)
Message-Id: <3DED8FD4.3539FB11@acm.org>

Bob X wrote:
> 
> "John W. Krahn" <krahnj@acm.org> wrote in message
> news:3DECDCCE.D3D1E4CA@acm.org...
> <snip>
> >
> > # pragmas
> > use strict;
> > use warnings;
> >
> > # modules
> > use Net::FTP;
> >
> > # my declares
> > my $hostname  = 'ftp.symantec.com';
> > my $navhome   =
> > '/public/english_us_canada/antivirus_definitions/norton_antivirus';
> > my $username  = 'anonymous';
> > my $password  = 'nobody@spammer.com';
> > my $local_dir = 'c:\temp';
> > my $net_dir   = 'p:\public\navtemp';
> >
> > my ( $day, $month, $year ) = ( localtime( time - 86_400 ) )[3, 4, 5];
> > # file name ex:  20021202-05-x86.exe
> > my $fileglob = sprintf '%04d%02d%02d*x86.exe', $year + 1900, $month + 1,
> > $day;
> 
> I do not see how this matches the file name example? The -05- is not a
> constant and I have no way of knowing what Symantec means by it. So I need
> to check for the first part of the file name (20021202) and the suffix
> (EXE).
> 
> When I run a test (on just the $fileglob) I get:  20021202*x86
> 
> That will not match a file.
> 
> > # connect to the ftp site
> > my $ftp = Net::FTP->new( $hostname ) or die "Cannot connect to
> > $hostname: $@\n";
> >
> > $ftp->login( $username, $password ) or die "Cannot log in to
> > $hostname\n";
> > $ftp->cwd( $navhome ) or die "Cannot change to directory $navhome\n";
> >
> > my @files = $ftp->ls( $fileglob ) or die "Cannot list remote files\n";
> > @files > 1 and warn "More than one file was found: @files\n";
> 
> I get the "Cannot list remote files" error but I think this is because the
> earlier $fileglob was missing the mark some and so there isn't a list of
> files to show.


It works fine on my system:

$ perl -we'
use strict;  
use Net::FTP;
           
my $hostname =
q[ftp.symantec.com];                                                                      
my $navhome  =
q[/public/english_us_canada/antivirus_definitions/norton_antivirus];
my $username =
q[anonymous];                                                                                                    
my $password = q[nobody@spammer.com];
my $fileglob = sprintf q[%04d%02d%02d*x86.exe], 2002, 12, 2;
                                                           
my $ftp = Net::FTP->new( $hostname ) or die "Cannot connect to
$hostname: $@\n";
                                                                                      
$ftp->login( $username, $password ) or die "Cannot log in to
$hostname\n";        
$ftp->binary or die "Cannott set binary mode\n";        
$ftp->cwd( $navhome ) or die "Cannot change to directory
$navhome\n";        
                                                                                   
my @files = $ftp->ls( $fileglob
);                                                 
                                                                                   
print
"@files\n";                                                                      
'
20021202-005-x86.exe




John
-- 
use Perl;
program
fulfillment


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

Date: Wed, 04 Dec 2002 03:17:36 -0800
From: palladium@spinn.net
Subject: Re: any cool script site???
Message-Id: <61pruus3c8017b0jleo36fmd4bsom5ukff@4ax.com>

Yeah.. Matt's Script Archive.....Everyone uses it !

Plink

Rodney
On 3 Dec 2002 04:32:01 -0800, keshavforever@rediffmail.com (keshav
prasad) wrote:

>Guys ...
>
>if you know any cool network script site.. please tell me



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

Date: Wed, 04 Dec 2002 10:47:14 GMT
From: helgi@decode.is (Helgi Briem)
Subject: Re: any cool script site???
Message-Id: <3deddc39.4260974106@news.cis.dfn.de>

On Wed, 04 Dec 2002 03:17:36 -0800, palladium@spinn.net
wrote:

First:
Don't top-post.  It is incredibly rude, annoys the
regulars and severely damages your reputation
and credibility in this forum.

>On 3 Dec 2002 04:32:01 -0800, keshavforever@rediffmail.com 
>(keshav prasad) wrote:

>>if you know any cool network script site.. please tell me
>

>Yeah.. Matt's Script Archive.....Everyone uses it !

Second:
Do not recommend Matt's Script Archive, it is a
repository of out-of-date, badly written scripts.

Try the NMS project at sourceforge:

http://nms-cgi.sourceforge.net/

for properly written replacements for
Matt's scripts.
-- 
Regards, Helgi Briem
helgi AT decode DOT is

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


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

Date: 3 Dec 2002 22:26:48 -0800
From: fumail@freeuk.com (qanda)
Subject: Re: C to perl, very large data files, efficiency, idioms.
Message-Id: <62b4710f.0212032226.6e7de45e@posting.google.com>

Hi All

First of all thanks for all the input.

In answer to queries people raised (mainly Tad - thanks again for
advice) ...

I mentioned C to perl converter - I'm sure I've seen this somewhere
but don't have access to much of my reference material at the moment
so sorry, no details yet.

As for the 'type of processing' by this I meant there will be a few
thousand files each with approximately 50000 records, each record
varies from 100 to 700 fields, fields are numeric (decimal and hex),
string, vector (ie with subfields).  The actual processing (at present
- not very good), first of all pre-processes the files to split into
different record types depending on the value of several fields
(unfortunately we have no control over the record format - a single
field for the record type would be ideal!)  Then within each group of
records we find matching records (by comparing several fields) then
either write both out or merge them depending on record type.

What I was looking for is a kind of perlism-pseudo code for how perl
would handle this.

We don't HAVE to read in the whole file (and may not be possible on
some systems) but I was curious to know of the pro's and con's in
perl.

thanks again guys and girls


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

Date: Wed, 04 Dec 2002 07:43:57 GMT
From: "Lois" <lois@hotmail.com>
Subject: child signal
Message-Id: <1niH9.22947$pN3.1037@sccrnsc03>

Hi all,

I have fork() some children to do some processings and I want to quit the
whole program when the first child finishes.

I thought it would be calling kill from the signal sub, but I am not sure
exit in the sub will quit the zombie or the main program. Anyway it didn't
work...

$SIG{CHLD} = \&zombie;


sub zombie
{
     exit 0;
}

what's the correct way to do this?


Thanks,
lois




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

Date: Wed, 04 Dec 2002 10:25:53 GMT
From: Logan Shaw <lshaw-usenet@austin.rr.com>
Subject: Re: child signal
Message-Id: <RKkH9.117198$8D.3011574@twister.austin.rr.com>

In article <1niH9.22947$pN3.1037@sccrnsc03>, Lois wrote:
> I have fork() some children to do some processings and I want to quit the
> whole program when the first child finishes.
> 
> I thought it would be calling kill from the signal sub, but I am not sure
> exit in the sub will quit the zombie or the main program. Anyway it didn't
> work...
    :
    :
> what's the correct way to do this?
 
Normally, you want to use wait().  Do a "perldoc -f wait".

When wait() returns, you should be able to use kill() on all the
children, except of course for the one that has already finished
(the process number is wait()'s return code).

(Or does your parent process need to keep running and not block?)

  - Logan


-- 
I'm currently looking for work as a Unix/Solaris
administrator, or Perl/C++/Java developer.  Resume
at http://home.austin.rr.com/logan/resume.html.


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

Date: 4 Dec 2002 08:55:24 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@post.rwth-aachen.de>
Subject: Re: child signal
Message-Id: <askfts$lrk$1@nets3.rz.RWTH-Aachen.DE>

Also sprach Lois:

> I have fork() some children to do some processings and I want to quit the
> whole program when the first child finishes.
> 
> I thought it would be calling kill from the signal sub, but I am not sure
> exit in the sub will quit the zombie or the main program. Anyway it didn't
> work...

It will in fact terminate the main program. However, all children not
yet terminated will continue with their work. Before quitting you should
therefore terminate all children. When you fork them off, you could save
their PIDs in an array and within this handler send a SIGTERM to each of
these PIDs: [untested]

    use POSIX ":sys_wait_h"; # for non-blocking wait
    our @pids;               # used to store the child pids 
    ...
    $SIG{CHLD} = sub {
        my @reaped;
        my $kid = waitpid -1, WNOHANG; # reap the first child process
        push @reaped, $kid;
        local $SIG{CHLD} = sub { push @reaped, waitpid(-1, WNOHANG) };
        kill TERM => $_ for @pids;
        1 while @pids != @reaped;      # ensure all children are reaped
        exit 0;
    };

I am not sure about the nested SIGCHLD handler. It might be necessary to
also reap each of the children you terminate in the for-loop. Hence you
need a different handler here.

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, 4 Dec 2002 02:52:50 -0800
From: btam01@ccsf.edu
Subject: Re: how to get it quoted?
Message-Id: <Pine.HPX.4.44.0212040250110.20819-100000@hills.ccsf.cc.ca.us>

On 3 Dec 2002, Walter Roberson wrote:

> In article <Pine.HPX.4.44.0212031248550.18091-100000@hills.ccsf.cc.ca.us>,
>  <btam01@ccsf.edu> wrote:
>
> :open(MAIL,"| mailx -s 'for test' c24b18d4bb4afdf052330678af9a601d+sent
> :mail\@neo.tamu.edu") does not work.

open(MAIL," |mailx -s 'for test' c24b18d4bb4afdf052330678af9a601d+sent

I'm sorry, what I meant was in my version of Perl, a space before the pipe
will not work.

-Bill



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

Date: Wed, 04 Dec 2002 14:00:09 +0800
From: teacraft <teacraft@163.com.blah>
Subject: Re: HTML parse & then get text WITH tags from between tags ?
Message-Id: <ask50h$bru$2@newstoo.ericsson.se>

John Smith wrote:

>Do you know if there's a way using HTML Parser or TokeParser etc. to parse
>an HTML document & then ask for all the text WITH tags between say <SUMMARY>
>& </SUMMARY> ?
>
>So I want to extract "<B>BOLD</B>" from between <SUMMARY></SUMMARY> below.
>
>I can't seem to find an easy way to get all text back WITH tags.
>
>- Sam.
>
>
><STORY>
>
><SUMMARY><B>BOLD</B></SUMMARY>
>
></STORY>
>
>
>  
>
Try HTML::TreeBuilder.



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

Date: 4 Dec 2002 00:00:56 -0800
From: ben.rogers@escalate.com (benrog)
Subject: passing data between perl scripts and a module: probably a basic question
Message-Id: <1da5d446.0212040000.1e6c0a07@posting.google.com>

Goal: write two scripts (one takes input and one prints processed
input) and one module (which processes the input)

I started out by putting all the code in one file just to get the
fundamentals in place. That was successful and all was ok. After
breaking the code up into the requisite pieces, nothing works. I am
thinking that my current vortex of ignorance centers around passing
values between subroutines, modules, and scripts.

Anyway, my three files are below. 

file one : takes input. Does not pass $userid to &makeDatabase I don't
think. I'm getting uninitialized value errors all over the place.

file two: well, all the work is done here. Everything worked when all
was in one file, so I'm assuming I just don't understand how to pass
values back and forth between the module and perl scripts.

file three: this doesn't do anything but call the &Menu in the module

Any ideas would be appreciated. 


FILE ONE -----------------------------------------------------------------
#!perl -w
#use strict; 
#my $userid; # User data
use Hits;

&getInput;
sub getInput {
print "Enter your USER ID:"; chomp ($userid = <STDIN>); # Letters &
not null
	$_ = $userid;
	if ( /[a-z]{8}/i && !/[0-9\W_]/ ) { print "Thank you for
visiting!\n";}
	else { print "You must enter an ID of 8 letters!\n"; &getInput;}
	&makeDatabase();
}


FILE TWO --------------------------------------------------------------------
#!perl -w
#use strict; 
#my $userid; my $hits = 0; my $lasttime;	# User data
my %DATABASE;					# DB file filehandle
my $database;					# Var for db filename
#my $menuitem;					# Menu options from STDIN
my $time; my $localtime;		# Epoch time and local time
my $key;			# Accesses key in hash
my @keys;			# For storing and sorting keys
my $row;			# For unpacking DB rows, joining, splitting
my @row;			# For storing $row
my @list; 			# Takes reordered $var to achieve new sort
my $var;			# For storing reordered user data in @list

package Hits;
use Exporter; 
@ISA = qw(Exporter);
@EXPORT = qw(&makeDatabase &printHits &dateReport &hitReport &Menu
%DATABASE $database);

sub makeDatabase() { ##### MAKE DATABASE 
	$database = "db2.dat";
	dbmopen (%DATABASE, $database, 0644) or warn "Cannot create database:
$!";
	if (!(exists $DATABASE{$userid})){ # If ID is new, make row: userid,
time, hits
		$time = time; $hits = 1; 
		@row = ($userid, $time, $hits);
		$row = join " ", @row; 
		$DATABASE{$userid} = pack "a*", $row;
	}
	else { # If ID does exist replace time; add one to hits
		$row = unpack "a*", $DATABASE{$userid};
		($userid, $time, $hits) = split / /, $row;
		$time = time; $hits += 1; 
		@row = ($userid, $time, $hits);
		$row = join " ", @row; 
		$DATABASE{$userid} = pack "a*", $row;
	}
	dbmclose (%DATABASE);
} #############################################

sub Menu { ### MENU SUBROUTINE: MENU WITH NAV OPTIONS
##################
	print "\n\n-----------OPTIONS-------------\n\n";
	print "    \"Control C\" to quit\;\n";
	print "    -?: Show menu\n    -u: Show user hits, date, and time\n   
-d: Print report sorted by date\n    -h: Print report sorted by
hits\n\n";
	print "-------------------------------\n\n\n";
chomp ($menuitem = <STDIN>);
	if 	  ($menuitem =~ /-\?/){ &Menu; } 
	elsif ($menuitem =~ /-u/i){ &printHits; }
	elsif ($menuitem =~ /-d/i){ &dateReport; }
	elsif ($menuitem =~ /-h/i){ &hitReport; }
	else  { print "Choose a menu option or press \"Control C\" to
quit.\n"; &Menu;}
	return $menuitem;
} ###################################################################

sub printHits() { ### For a single user, print hits, date and last
access time.
	print "\nEnter User ID to display synopsis:"; chomp ($userid =
<STDIN>);
	dbmopen (%DATABASE, $database, 0644);
	if (exists $DATABASE{$userid}){
		$lasttime = localtime($time);
		print "\n    USERID: $userid\n      HITS: $hits\nLAST VISIT:
$lasttime.\n\n";}
	else { print "User does not exist. Enter a valid USER ID:\n\n"; #
Must enter valid ID
		sub alpha { lc ($DATABASE{$a}) cmp lc ($DATABASE{$b}); }
		if (@keys = sort alpha keys %DATABASE) { 
			foreach (@keys) { print "      $_\n"; } &printHits;} 
	# elsif ($userid eq '') { print "User does not exist. Try again.\n";}
This could be
	# a separate check between if and elsif, but the above check is more
elegant and offers
	# the user a list of valid values for both null and invalid entries. 
	dbmclose (%DATABASE);
&Menu;
} ###################################################################

sub dateReport() { ### Sort by descending last access date: print
userid, hits, date ####
	dbmopen (%DATABASE, $database, 0644);	
	while (my ($key, $value) = each (%DATABASE)){ 
		($userid, $time, $hits) = split / /, $value;
		$lasttime = localtime($time);
		$var = join (" ", $lasttime, $userid, $hits);
		push (@list, $var);
	}
		@list = sort (@list); @list = reverse (@list);
			foreach (@list) { print "$_\n"; }
	dbmclose (%DATABASE);
&Menu;  
} #############################################################################

sub hitReport() { ### Sort by descending # of hits: print userid,
hits, date
	dbmopen (%DATABASE, $database, 0644);
	while (my ($key, $value) = each (%DATABASE)){ 
		($userid, $time, $hits) = split / /, $value;
		$lasttime = localtime($time);
		$var = join (" ", $hits, $lasttime, $userid);
		push (@list, $var);
	}
		@list = sort (@list); @list = reverse (@list);
			foreach (@list) { print "$_\n"; }
	dbmclose (%DATABASE);  
&Menu;
} }####################################################################
1;

FILE THREE ---------------------------------------------------
#!perl -w
#use strict; 
use Hits;

&Menu;


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

Date: 3 Dec 2002 22:52:16 -0800
From: paul_newsgroups@yahoo.ca (Paul R.)
Subject: PeggyPro IDE/Editor
Message-Id: <5814d00e.0212032252.7c5d5246@posting.google.com>

To the software tool and economically challenged among us...

For those looking for an IDE/Editor/Programming Environment/Project
Manager...,
here's one even I could afford: PeggyPro
(Even so I got my boss to pay for it!)

Runs about 2500yen for the basic, 4500yen Professional, and 6500yen
with Oracle support. That's near $25 $45 and $65 (Depending on the
exchange rate and your
country). I use the PeggyPro as it includes CVS support.
There's a free text editor too, but I didn't use that (PeggyPad).

I used to use Codewright, but a Japanese Co-worker showed me this.
Its a fraction of the cost, has similar features, some easier and some
a bit more difficult to use.
Easy install - read the online docs.
Easy Project setup - Just drag your directory tree onto the project
window/panel.

No English help yet, its still in Beta, but I didn't really need it -
most things are obvious. You can get a copy of the key-bindings file -
that gives a summary of the available commands. If you read the Online
Install Notes carefully, you'll get insite to a lot of the commands.

Links great with CVS (we use CVSNT on Win2000) - Although we had to
delete the cvs.exe file that it came with so it would use the newer
one from CVSNT or TortoiseCVS.


Home:      http://www2.noritz.co.jp/anchor/index.html
English:   http://www2.noritz.co.jp/anchor/ashp/peggy_enu/pegindex.html

Some Notes:: 
  Side by side step through of file compare using F4
  Right Click a file in the project window, Properties, 
    File Tab, Tool Action 
    -easy setup of ToolBar Button 
    -Super easy to add tools/compilers, 
      just put the program in the project
  Multi file search or search/replace
  Can use the EMail Quotes >> << buttons to Indent/outdent a block
    with any string - I set it to // for C/C++
  Group refers to a folder in the project window, 
    Group-deep recurses the folders.
  Language Highlighting works for the Normal C, Fortran..., 
    and also specials like HTML, Perl, DOS Batch, and other scripts
  Language Highlighting for implementations of C and Assembler 
   used in CPU/MPU/Microcontrollers 

Paul
Sanyo
Address for NewsGroups: paul_newsgroups_NOT_HERE@yahoo.ca  
( delete the _NOT_HERE )

Posted to: (Please only reply to post in: comp.editors)
comp.editors,comp.arch.embedded,comp.lang.asm.x86,
comp.lang.perl.misc,comp.lang.c,microsoft.public.vc.ide_general


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

Date: Wed, 04 Dec 2002 03:17:35 -0800
From: palladium@spinn.net
Subject: Re: Perl Packages question
Message-Id: <3joruugpqnjtgsvcqed2jddk7jgbt2igrd@4ax.com>

Just as an add on to the fine information already provided. 

you can run 

perl -MCPAN -eshell 

and get an interactive Module Installation console.

Just make sure you have everything required to use it properly.

perldoc CPAN 
explains much about the subject.

make sure you have make or nmake on win32 sourced in the environment
path.


HTH,

Rodney

On 3 Dec 2002 09:20:03 -0800, kasp@epatra.com (Kasp) wrote:

>I am quite new to Perl and still am grasping the basics. I have seen
>many code use packages like IO::File and Mail::Mailer etc etc.
>
>The question I had:-
>
>1. How and from where can I get Perl Packages like Mail::Mailer etc.
>From CPAN? But where exactly?
>
>2. How do I install these packages and start using them? A small
>example would be greatly appreciated.
>
>Thanks
>Kasp.



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

Date: 4 Dec 2002 02:26:57 -0800
From: pjacklam@online.no (Peter J. Acklam)
Subject: Re FAQ: How can I capture STDERR from an external command?
Message-Id: <fe4612a5.0212040226.4aba4e19@posting.google.com>

> 8.25: How can I capture STDERR from an external command?
> 
> [...]
>
>   To read both a command's STDOUT and its STDERR separately, it's easiest
>   and safest to redirect them separately to files, and then read from
>   those files when the program is done:
> 
>     system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");

That's what I need, except I need cycling of the output files,
like what is done with /var/adm/messages (at least on Solaris).

(By "cycling" I mean that when the size of the first set of output
files (one for each of stdout and stderr) has reached a certain
limit, then I close the "program.stdout", shift the list of files,
so that the old "program.0.stdout" becomes "program.1.stdout", and
"program.stdout" becomes "program.0.stdout". etc., and then I open
"program.stdout" for writing again.)

How about if I create two FIFO files and let the output files be
the two FIFOs?  Then, my Perl program can read from the two FIFOs
and write to the output files and also handle the cycling of the
regular output files.

What are the dangers and disadvantages of this approach compared
to using IPC::Open3.  To me, using FIFO files seems much cleaner,
but since no-one else seems to have suggested it, I'm afraid there
are some disadvantages that I have missed...  :-)

Comments, anyone?

Peter


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

Date: Wed, 04 Dec 2002 10:14:43 GMT
From: matt <linuxnb@yahoo.com>
Subject: Re: Regular expressions
Message-Id: <nAkH9.224500$NH2.15369@sccrnsc01>

Gary wrote:

> Hi
>     Could one of you point me in the right direction for learning more
>     about
> the perl regular expressions?
> 
> i have a book which involves the m// & s// and i don't understand the use
> of *, ?, + etc.
> 
> Any help appreciated
> 
> Cheers
> 
> Gary


for(q(please dont)){print $_,$3,$5,$4,$1,$3,$1,$4,$2,$5 if 
/(\w)\w{3,3}(\w)\w( )\w(\w)\w(\w)/;}

Thanks :-)

Matt 




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

Date: 4 Dec 2002 10:28:06 GMT
From: Stephen Patterson <s.patterson@freeuk.com>
Subject: Warnings when creating an array of hashes
Message-Id: <slrnaurm5m.md9.s.patterson@seagoon.localdomain>

I've got this code generating an array of hashes. It works fine, but if I
turn on warnings (-w), I get "Useless use of a constant in void context" and
"Useless use of array element in void context" both within 
$queue[$i] = ( ... ). 

    # make the queue into an array of hashes
    for (my $i = 0; $i < @queue; ++$i) {
        $queue[$i] =~ s/\s+/ /g; # remove extraneous spaces
        my @job = split / /, $queue[$i];
        $queue[$i] = (Rank  => $job[0],
                      Owner => $job[1],
                      Job   => $job[2],
                      Files => $job[3],
                      Size  => $job[4]
                     );
     }

Does anyone know how to solve this without turning off warnings (-w)?
-- 
Stephen Patterson http://www.lexx.uklinux.net http://patter.mine.nu
steve@SPAM.lexx.uklinux.net  remove SPAM to reply        
Linux Counter No: 142831 GPG Public key: 252B8B37        
Last one down the pub's an MCSE


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

Date: 4 Dec 2002 10:49:12 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@post.rwth-aachen.de>
Subject: Re: Warnings when creating an array of hashes
Message-Id: <askmj8$sd1$1@nets3.rz.RWTH-Aachen.DE>

Also sprach Stephen Patterson:

> I've got this code generating an array of hashes. It works fine, but if I
> turn on warnings (-w), I get "Useless use of a constant in void context" and
> "Useless use of array element in void context" both within 
> $queue[$i] = ( ... ). 

Actually it's not working fine at all. :-) This is a good example where
warnings can save your life. The warning you get is anything but
spurious.

>     # make the queue into an array of hashes
>     for (my $i = 0; $i < @queue; ++$i) {
>         $queue[$i] =~ s/\s+/ /g; # remove extraneous spaces
>         my @job = split / /, $queue[$i];
>         $queue[$i] = (Rank  => $job[0],
>                       Owner => $job[1],
>                       Job   => $job[2],
>                       Files => $job[3],
>                       Size  => $job[4]
>                      );

What seemingly happens here is an assignmet of a list to a scalar. Yet,
we know there are no lists in scalar context so the above does something
quite else. It is equivalent to:

    "Rank", $job[0], "Owner", $job[1], "Job", 
    $job[2], "Files", $job[3], "Size",
    $queue[$i] = $job[4];
    
So you have nine values in void context and an assignment of one value
to $queue[$i]. Now you see why this was no list at all. It was merely
the comma operator used in scalar context: 10 statements evaluated from
left to right, the first nine thrown away.

The solution is simply to replace round parens with curlies to create a
reference to an anonymous hash and store this on $queue[$i]:

    $queue[$i] = { Rank  => $job[0],
                   Owner => $job[1],
                   Job   => $job[2],
                   Files => $job[3],
                   Size  => $job[4], };

$queue[$i] now holds a hash-reference. Access can happen in different
ways:

    my %hash = %{ $queue[$i] };     # whole hash
    my $value = $queue[$i]->{Rank}; # single value
    
> Does anyone know how to solve this without turning off warnings (-w)?

Shutting up warnings would indeed have been the worst possible solution.

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: 4 Dec 2002 10:57:53 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@post.rwth-aachen.de>
Subject: Re: Warnings when creating an array of hashes
Message-Id: <askn3h$su9$1@nets3.rz.RWTH-Aachen.DE>

Just realized that I forgot something to mention.

Also sprach Stephen Patterson:

>     # make the queue into an array of hashes
>     for (my $i = 0; $i < @queue; ++$i) {
>         $queue[$i] =~ s/\s+/ /g; # remove extraneous spaces
>         my @job = split / /, $queue[$i];
>         $queue[$i] = (Rank  => $job[0],
>                       Owner => $job[1],
>                       Job   => $job[2],
>                       Files => $job[3],
>                       Size  => $job[4]
>                      );
>      }

The above (after it has been corrected) can be made shorter by using a
hash-slice. The idea is that you can set multiple hash-values with one
statement. Also, the foreach-loop can be written more Perlishly:

    for my $i (@queue) {
        $i =~ s/\s+/ /g;
        my %h; @h{ qw/Rank Owner Job Files Size/ } = split / /, $i;
        $i = \%h;
    }

It also makes use of the fact that the loop variable is actually an
alias for the value of the array you are iterating over. So changing $i
changes the corresponding array element.

Hash-slices are so useful that everyone should read about them
instantly. See 'perldoc perldata', the section "Slices".

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, 4 Dec 2002 03:24:09 -0700
From: "Michael D. Carey" <michael@giantsquidmarks.com>
Subject: Win32 and *NIX, cryptographically secure random numbers with PERL
Message-Id: <3dedd730_3@spamkiller.newsgroups.com>

Can someone suggests a method to generate cryptographically
secure random numbers in PERL?  This method must function on
both Win32 (ActiveState) and *NIX.  I need a function to
generate keys for Symmetric Ciphers.

I wish Win32 had /dev/random.  Thanks in advance...




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

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


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