[29006] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 250 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Mar 21 21:14:19 2007

Date: Wed, 21 Mar 2007 18:14:13 -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, 21 Mar 2007     Volume: 11 Number: 250

Today's topics:
        Stuck trying to pass an array that contains a hash to a novak.dl@gmail.com
    Re: Stuck trying to pass an array that contains a hash  <jgibson@mail.arc.nasa.gov>
    Re: upload method not returning undef? <noreply@gunnar.cc>
    Re: Using @ARGV in object oriented script <ben@morrow.me.uk>
        variable evaluation and printing <chadw3@gmail.com>
    Re: variable evaluation and printing <someone@example.com>
    Re: variable evaluation and printing <jgibson@mail.arc.nasa.gov>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: 21 Mar 2007 15:54:41 -0700
From: novak.dl@gmail.com
Subject: Stuck trying to pass an array that contains a hash to another subprogram
Message-Id: <1174517681.408621.226270@e65g2000hsc.googlegroups.com>

 am modifying a Perl program and I'm stuck trying to pass an array
that contains a hash to another subprogram.

I have the following code  (I will keep this as brief as possible
without leaving out any relevant pieces).

#Global Variables
my $new_decal_number = ' ';
my @citationpermit =();
my $cit_key = ();
 ...

main();

sub main
{
 ...
@citationpermit = prefix_citation_permits();

if ($counter > 0)
    {
print("Number of citations to process: $counter \n");

###Cycle thru citations to update Citation_Main table
        foreach $cit_key(@citationpermit) {
                      &updatecitation($cit_key);
 ...

sub prefix_citation_permits()
{
#     statement handle
my @row = ();
my ($sth,@rows);
$sth=$dbh->prepare("SELECT cm.Citation_Key,
                                             cm.Number,
                                             cm.Decal_Number,
                                             ISNULL(per.Last_Name, '
'),
                                             ISNULL(per.First_Name, '
'),
 ...
while (@row=$sth->fetchrow_array ) {
             $new_decal_number = ($permit_prefix_parm . '-' .
$row[2]);
             print ("New Citation Decal Number: $new_decal_number
\n");
             $counter += 1;
             push @rows, {'citation_key' => $row[0],
                            'citation_number' => $row[1],
                            'decal_number' => $row[2],
                            'last_name' => $row[3],
                            'first_name' => $row[4],
                            'middle_name' => $row[5],
                            'local_id' => $row[6],
                            'new_decal_number'=> $new_decal_number};
                       }
 return @rows;
}

sub updatecitation()
{
#     statement handle
$rc1=0;
$rc2=0;


 print("Old decal_number: $cit_key->{'decal_number'} \n");
 print("New decal_number: $cit_key->{'new_decal_number'} \n");
 ...

Perl complains with the print("Old decal...) line with:
Use of uninitialized value in concatenation (.) or string at
permitprefix_test2.pl line 684.
Old decal_number:

It appears that it can't read the hash value in the updatecitation
subprogram. If I change the foreach to not run the subprogram
updatecitation and do the logic there, it works:

###Cycle thru citations to update Citation_Main table
        foreach $cit_key(@citationpermit) {
#                      &updatecitation($cit_key);
         print("Old decal_number: $cit_key->{'decal_number'} \n");
         print("New decal_number: $cit_key->{'new_decal_number'} \n");
 ...

Can anyone assist me in how to pass the array of hashes to the
subprogram updatecitation?



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

Date: Wed, 21 Mar 2007 16:59:46 -0700
From: Jim Gibson <jgibson@mail.arc.nasa.gov>
Subject: Re: Stuck trying to pass an array that contains a hash to another subprogram
Message-Id: <210320071659468369%jgibson@mail.arc.nasa.gov>

In article <1174517681.408621.226270@e65g2000hsc.googlegroups.com>,
<novak.dl@gmail.com> wrote:

>  am modifying a Perl program and I'm stuck trying to pass an array
> that contains a hash to another subprogram.
> 
> I have the following code  (I will keep this as brief as possible
> without leaving out any relevant pieces).

It helps to include a complete minimal program. In your case, leaving
out the database access and focusing on the passing of variables would
have helped. It also helps to use minimal and consistent indenting.

> 
> #Global Variables
> my $new_decal_number = ' ';
> my @citationpermit =();
> my $cit_key = ();

Initializing a scalar to an empty list is unnecessary and confusing.

> ...
> 
> main();

Do you always make your Perl programs look like C?

> 
> sub main
> {
> ...
> @citationpermit = prefix_citation_permits();
> 
> if ($counter > 0)
>     {
> print("Number of citations to process: $counter \n");
> 
> ###Cycle thru citations to update Citation_Main table
>         foreach $cit_key(@citationpermit) {
>                       &updatecitation($cit_key);

The variable $cit_key here is not the global you have declared above.
It is a lexical variable that is aliased to each element of the
@citationpermit array. This would be OK since you are passing its value
to the updatecitation subroutine, except in that routine you do not use
the argument you have passed. Also, the '&' is unnecessary and make you
look like a Perl4 programmer.

> ...
> 
> sub prefix_citation_permits()
> {
> #     statement handle
> my @row = ();
> my ($sth,@rows);
> $sth=$dbh->prepare("SELECT cm.Citation_Key,
>                                              cm.Number,
>                                              cm.Decal_Number,
>                                              ISNULL(per.Last_Name, '
> '),
>                                              ISNULL(per.First_Name, '
> '),
> ...
> while (@row=$sth->fetchrow_array ) {
>              $new_decal_number = ($permit_prefix_parm . '-' .
> $row[2]);
>              print ("New Citation Decal Number: $new_decal_number
> \n");
>              $counter += 1;
>              push @rows, {'citation_key' => $row[0],
>                             'citation_number' => $row[1],
>                             'decal_number' => $row[2],
>                             'last_name' => $row[3],
>                             'first_name' => $row[4],
>                             'middle_name' => $row[5],
>                             'local_id' => $row[6],
>                             'new_decal_number'=> $new_decal_number};
>                        }
>  return @rows;
> }
> 
> sub updatecitation()
> {

You need to access the variable passed as an argument to this routine.
Maybe something like:

  my $cit_key = shift;

(but better to pick a new name).

> #     statement handle
> $rc1=0;
> $rc2=0;
> 
> 
>  print("Old decal_number: $cit_key->{'decal_number'} \n");
>  print("New decal_number: $cit_key->{'new_decal_number'} \n");

(Change the name of $cit_key to the same thing here.)

> ...
> 
> Perl complains with the print("Old decal...) line with:
> Use of uninitialized value in concatenation (.) or string at
> permitprefix_test2.pl line 684.
> Old decal_number:

 ... because the global $cit_key never gets any values.

> 
> It appears that it can't read the hash value in the updatecitation
> subprogram. If I change the foreach to not run the subprogram
> updatecitation and do the logic there, it works:
> 
> ###Cycle thru citations to update Citation_Main table
>         foreach $cit_key(@citationpermit) {
> #                      &updatecitation($cit_key);
>          print("Old decal_number: $cit_key->{'decal_number'} \n");
>          print("New decal_number: $cit_key->{'new_decal_number'} \n");
> ...

 ... because the $cit_key here is the localized one that is aliased to
an element of @citationpermit, which does have values.

> 
> Can anyone assist me in how to pass the array of hashes to the
> subprogram updatecitation?
> 

Hope I have done so.

 Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
    ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------        
                http://www.usenet.com


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

Date: Thu, 22 Mar 2007 00:46:19 +0100
From: Gunnar Hjalmarsson <noreply@gunnar.cc>
Subject: Re: upload method not returning undef?
Message-Id: <56dui8F26h5hdU1@mid.individual.net>

Suk wrote:
> I want to be sure that if a user enters an invalid filename (i.e one
> that doesnt exist) in a webform an error is returned. In the CGI
> documentation it says the upload( ) method should return undef for an
> invalid filehandle,

The handle isn't necessarily invalid if the file is empty.

> Here is the script im using:-
> 
> #!/usr/local/bin/perl
> use strict;
> use warnings;
> use CGI qw(:standard);
> 
> our $upload_dir = "/tmp";
> our $filename;
> our $upload_filehandle;
> our $message="Thank you";
> 
> $filename = param("file");
> $filename =~ s/.*[\/\\](.*)/$1/;
> 
> $upload_filehandle = upload("file");
> 
> die "Invalid filehandle" if (!defined($upload_filehandle));
> 
> open UPLOADFILE, ">$upload_dir/$filename";
> 
> binmode UPLOADFILE;
> 
> while ( <$upload_filehandle> )
> {
>   print UPLOADFILE;
> }
> 
> close UPLOADFILE;

You may want to try something like this here:

     unless ( -s "$upload_dir/$filename" ) {
         unlink "$upload_dir/$filename";
         die "Invalid filename";
     }

> print header;
> print <<END_HTML;
> <HTML>
> <HEAD>
> <TITLE>Thank you for your upload</TITLE>
> <script type="text/javascript">
>         alert("$message");
> </script>
> </HEAD>
> <BODY>
> </BODY>
> </HTML>
> END_HTML
> 
> The "die" seems to be ignored, and I get an empty file in /tmp if I
> enter a non-existent file in the webform?

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl


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

Date: Wed, 21 Mar 2007 22:09:33 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Using @ARGV in object oriented script
Message-Id: <t1n8d4-uaa.ln1@osiris.mauzo.dyndns.org>


Quoth "Klaus" <klaus03@gmail.com>:
> On Mar 21, 5:36 pm, "Jorge" <awks...@yahoo.com> wrote:
> > As an exercise in learing Object Oriented Perl I am creating a class
> > and a calling script which simply checks the command line arguments to
> > see if each file is present. So far it appears to be working as
> > expected but I have a question about the use of @ARGV in my calling
> > script.
> >
> > The only way I could see to pass @ARGV as an object was to make it a
> > scalar ... thus the line ...
> >
> > my $list_of_files = join ' ', @ARGV;
> >
> > Is there a way I can use a reference such as \@ARGV and somehow
> > derference it in the package?
> 
> I am not so familiar with object-oriented programming, but
> dereferencing \@ARGV in a simple subroutine should work the same way:

Methods work exactly the same as subs once they have been called. The
only difference is in how the method is located and called.

> ====================================================
> use strict;
> use warnings;
> 
> print do{ local $" = "', '"; "Before sub test(): \@ARGV = ('@ARGV')
> \n"; };

I realise this is not the point of your post :), but this is
unnecessarily ugly. Since it's only a tiny program, just set $" and have
done:

    $" = "', '";
    warn "Before sub test(): \@ARGV = ('@ARGV')";

You could probably omit the 'Before sub test()' as well: the line number
given by warn is clear enough, or use Carp::cluck.

> 
> test_ARGV(\@ARGV);
> 
> print "Test program finished.\n";
> 
> sub test_ARGV {
>     my @Array = @{$_[0]};

I don't know if you realise, but this makes a *copy* of the passed in
array. With large arrays, or if you are wanting to modify the array
in-place, you want something more like

    my ($Array) = @_;
    warn "\@Array = ('@$Array')";

>     print do{ local $" = "', '"; "Inside sub test(): \@Array =
> ('@Array')\n"; }
> }

Ben

-- 
For far more marvellous is the truth than any artists of the past imagined!
Why do the poets of the present not speak of it? What men are poets who can
speak of Jupiter if he were like a man, but if he is an immense spinning
sphere of methane and ammonia must be silent? [Feynmann]     ben@morrow.me.uk


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

Date: 21 Mar 2007 16:20:51 -0700
From: "manunderstress" <chadw3@gmail.com>
Subject: variable evaluation and printing
Message-Id: <1174519251.421961.121450@d57g2000hsg.googlegroups.com>

in the code below, why will it print (and add to the hash) $status but
not $ifconfig? Also when $status = "Production"; it fails to print or
add to hash as well.

something about variable evaluation/interpretation i'm not
understanding?

#ifconfig command on a solaris box; outputs multiple lines of text
my $ifconfig=`ifconfig -a`;
my $status='Production';

my @params = qw(status ifconfig);
foreach $item (@params) {

	if (defined $item) {
		print "item name: $item item value:". ${$item}. "\n";
		$post_checks{"$item"} = "${$item}";
	}
}



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

Date: Wed, 21 Mar 2007 23:39:49 GMT
From: "John W. Krahn" <someone@example.com>
Subject: Re: variable evaluation and printing
Message-Id: <9njMh.460$x9.1@edtnps89>

manunderstress wrote:
> in the code below, why will it print (and add to the hash) $status but
> not $ifconfig? Also when $status = "Production"; it fails to print or
> add to hash as well.
> 
> something about variable evaluation/interpretation i'm not
> understanding?
> 
> #ifconfig command on a solaris box; outputs multiple lines of text
> my $ifconfig=`ifconfig -a`;
> my $status='Production';
> 
> my @params = qw(status ifconfig);
> foreach $item (@params) {
> 
> 	if (defined $item) {
> 		print "item name: $item item value:". ${$item}. "\n";
> 		$post_checks{"$item"} = "${$item}";
> 	}
> }


It looks like you want to do this instead:


my %post_checks = (
    status   => 'Production',
    ifconfig => scalar `ifconfig -a`,
    );



(The answer to your question is in: perldoc -q "How can I use a variable as a
variable name"; but don't do that.)



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, 21 Mar 2007 17:14:33 -0700
From: Jim Gibson <jgibson@mail.arc.nasa.gov>
Subject: Re: variable evaluation and printing
Message-Id: <210320071714331572%jgibson@mail.arc.nasa.gov>

In article <1174519251.421961.121450@d57g2000hsg.googlegroups.com>,
manunderstress <chadw3@gmail.com> wrote:

> in the code below, why will it print (and add to the hash) $status but
> not $ifconfig? Also when $status = "Production"; it fails to print or
> add to hash as well.
> 
> something about variable evaluation/interpretation i'm not
> understanding?
> 
> #ifconfig command on a solaris box; outputs multiple lines of text
> my $ifconfig=`ifconfig -a`;
> my $status='Production';
> 
> my @params = qw(status ifconfig);
> foreach $item (@params) {
> 
>   if (defined $item) {
>     print "item name: $item item value:". ${$item}. "\n";
>     $post_checks{"$item"} = "${$item}";
>   }
> }
> 

You are trying to use symbolic references, and have demonstrated one
reason they are not recommended (they only work on global variables and
your variables are lexical).

See 'perldoc -q variable

     How can I use a variable as a variable name?

for other reasons why not to do this. Use a hash, instead.

-- 
Jim Gibson

 Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
    ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------        
                http://www.usenet.com


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

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 V11 Issue 250
**************************************


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