[19064] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 1259 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Jul 6 21:05:34 2001

Date: Fri, 6 Jul 2001 18:05:09 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <994467909-v10-i1259@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Fri, 6 Jul 2001     Volume: 10 Number: 1259

Today's topics:
    Re: Can someone translate this Perl into common English (Tad McClellan)
    Re: Correct way to open a .jpg image and save? (Martien Verbruggen)
    Re: Create unique file in dir? (Martien Verbruggen)
        FAQ: What are perl4 and perl5? <faq@denver.pm.org>
    Re: how to read multipart/form-data <mail@enricong.com>
    Re: MySQL,DBI doesn't like my 'LIKE' query <djberg96@hotmail.com>
        problem with data.. <ddunham@redwood.taos.com>
        Problems moving from an Apache server to a Windows serv <kerry@shetline.com>
    Re: Problems moving from an Apache server to a Windows  <wyzelli@yahoo.com>
    Re: Stumped on Text extraction\REGEX problem (Tad McClellan)
    Re: Stumped on Text extraction\REGEX problem <bart.lateur@skynet.be>
    Re: Using a hash passed by reference inside a function? <qumsieh@sympatico.ca>
    Re: Using a hash passed by reference inside a function? <miscellaneousemail@yahoo.com>
    Re: Using a hash passed by reference inside a function? (Tad McClellan)
    Re: Using a hash passed by reference inside a function? <krahnj@acm.org>
    Re: web fetching <buggs-clpm@splashground.de>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Fri, 6 Jul 2001 17:39:01 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Can someone translate this Perl into common English *grin*??
Message-Id: <slrn9kcbvk.kka.tadmc@tadmc26.august.net>

Stephen Collyer <scollyer@dont.spam.me.netspinner.co.uk> wrote:
>
>Carlos C. Gonzalez <miscellaneousemail@yahoo.com> wrote in message
>news:MPG.15afbfc9bba26152989683@news.edmonton.telusplanet.net...
>
>> while (($k, $v) = each %h)
>>   { print "$k -> $v\n" }
>>
>> I am guessing that the above means something like this.  Take each of the
>> values in the %h hash, store the index value in the $k scalar, the value
   ^^^^^^
   ^^^^^^  key/value pairs

>> associated with the index key value in the $v scalar and then for each
>> key/value pair in %h print the key (stored in $k) and the value (stored
>> in $v.
>
>That's precisely what it means. 


Right. It makes output identical to:

   foreach ( keys %h ) {
      print "$_ -> $h{$_}\n";
   }


>However, more can be said about *why*
>the loop works.


And *even more* can be said about why each() was chosen instead
of keys().


>The important point to be aware of is that the test of the while loop
>is executed in scalar context.

[snip very good explanation of context]


I hardly ever use each(). I just like the keys() approach better...

 ...except when the hash is tied to a disk file (I think the OP 
mentioned that his hash is tied).

keys() must iterate over the entire hash to build up the list
of keys to return. When each iteration involves disk I/O, this
can take A Long Time.

each() does not need to iterate to form its return value. It will
be noticably (when tied) faster than keys().


>Whew.


Tell that to the folks that think "programming is easy"   :-)


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


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

Date: Sat, 7 Jul 2001 08:37:41 +1000
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Correct way to open a .jpg image and save?
Message-Id: <slrn9kcfdl.tjn.mgjv@martien.heliotrope.home>

[Please put your reply after the text you quote. It's the generaly
accepted quoting convention on this group, and Usenet in general. It
makes long threads easier to follow.]

[Re-arranged both previous followups to be a bit more chronological]

On Fri, 6 Jul 2001 10:35:53 +0100,
	Matt L. <mlaw@talk21.comNOSPAM> wrote:

> [An unattributed poster said:]

>> "Matt L." <mlaw@talk21.comNOSPAM> wrote in message
>> news:9i29rq$e0$1@neptunium.btinternet.com...
>> > Hi!
>> >
>> > On a previous post I was advised not to open an image file like so:-
>> >
>> > $file = param('file');
>> > open (SAVE, ">../images/$file") || die $!;
>>
>>    binmode(SAVE);
>>
>> > while (<$file>) {
>> >     print SAVE $_;
>> > }

With the binmode, this should be ok, although many people will indeed
use read when they process binary data. Using the angle operators to
read data will read everything up to the next input record separator
(newline by default). Binary data may, or may not, have one of those.
That means that you potentially could be reading in the whole file at
once. In Perl, as long as you have enough memory, that isn't as much of
a problem, but it's a bit untidy. Programmers like to know what is going
on, and code like this does unpredictable things, that depend on the
data fed to it, and the amount of free memory in the system.

>> > But instead, I should use the function read(), I have the Perl cookbook
>> > which says to use this for fixed length records by doing this:-
>> >
>> > until ( eof(FILE) )  {
>> >         read(FILE, $record, $recordsize) == $RECORDSIZE 
>> >             or die "short read\n";
>> >       @FIELDS = unpack($TEMPLATE, $record);
>> > }

Yes, this is a little recipe that can be used to unpack binary data,
if you're interested in the content. If you are not interested in the
content, and just want to copy, pick a suitable size (8 kb or so), read
the blocks, and write them again. I'll also include an error check,
which will tell you whether the reads were all succesful. I'll use a
slightly different approach, which doesn't use eof().

This little snippet of code is a full Perl program, that takes two
arguments: A file to copy from, and a file to copy to. It copies the
data in binary format, in 8 kb chunks.

#!/usr/local/bin/perl -w
use strict;

@ARGV == 2 || die "2 Arguments needed\n";

open(IN, $ARGV[0]) || die $!;
binmode IN;
open(OUT, ">$ARGV[1]") || die $!;
binmode OUT;

my ($buffer, $nb);

print OUT $buffer
	while ($nb = read(IN, $buffer, 8192));

warn "Read error: $!" unless defined $nb;

close OUT;
close IN;


>> If you use binmode to read in and write out the format of the jpg file
>> remains correct.
> 
> I'd been led to believe that binmode was for non-unix like systems such as
> Windows?

binmode is used in all programs that care about portability, and
code-clarity. It indicates both to the system and to the programmer
reading your code that the data read is binary, i.e. that there should
be no translations done on the data to represent it in an internal form.

On unices, binmode is a noop. On windows it isn't. That does not mean
that you shouldn't use it in your programs on Unix. For the reasons
mentioned above, you should always use binmode when your data is not
text.

BTW, this is all clearly stated in the entry for binmode in the perlfunc
documentation.

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | We are born naked, wet and hungry.
Commercial Dynamics Pty. Ltd.   | Then things get worse.
NSW, Australia                  | 


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

Date: Sat, 7 Jul 2001 08:12:59 +1000
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Create unique file in dir?
Message-Id: <slrn9kcdvb.tjn.mgjv@martien.heliotrope.home>

On Sun, 01 Jul 2001 08:18:10 -0400,
	Benjamin Goldberg <goldbb2@earthlink.net> wrote:
> Zur Aougav wrote:
>> 
>> P.S. Lock and retry (with a new name) is a must in multi-processor
>> environment. Safe coding (even if you don't have this kind of
>> environment) is highly recommended.
> 
> Or better yet, use the O_EXCL flag with sysopen.
> use Fcntl;
> sub mktmp {
> 	my $a = "/tmp/" . time . "." . $$ . rand . ".";
> 	my $b = "0";
> 	my $fh;
> 	++$b until sysopen $fh, $a.$b, O_CREAT | O_EXCL | O_RDWR;
> 	if( wantarray ) {
> 		return ($fh, $a.$b);
> 	} else {
> 		unlink $a.$b;
> 		return $fh;
> 	}
> }

In this case, the file is always created in /tmp, and therefore not on
an NFS mount. However, the above isn't a general recipe that works in
all cases.

The use of O_EXCL on NFS mounted file systems can be, and in many cases
is, very unreliable. In that case, the standard recipe is to use a file
with a unique name (including hostname and pid, for example) to use as a
lockfile. However, now we're back to the original problem :)

> Having the rand() in there makes it highly likely to succeed on the
> first try, having the counter ($b) makes it so that if it doesn't
> succeed at first, it will eventually, assuming /tmp/ is writable.

*nod* I've used this approach in multithreaded and multi-process
applications before. One of them has been in production for years,
without ever creating a conflict, but reating many files with names that
has an incremented serial number, showing me that there would have been
a conflict if the precautions weren't taken. And this would even happen
on times that the application had very little to do. The point of this
last sentence of course being that defensive programming like this is
not only for those who write high-traffic applications. If you leave a
chance for collision open, then some day it will happen.

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | life ain't fair, but the root
Commercial Dynamics Pty. Ltd.   | password helps. -- BOFH
NSW, Australia                  | 


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

Date: Sat, 07 Jul 2001 00:17:02 GMT
From: PerlFAQ Server <faq@denver.pm.org>
Subject: FAQ: What are perl4 and perl5?
Message-Id: <2ys17.35$T3.170759168@news.frii.net>

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with every Standard Distribution of
Perl.

+
  What are perl4 and perl5?

    Perl4 and perl5 are informal names for different versions of the Perl
    programming language. It's easier to say "perl5" than it is to say "the
    5(.004) release of Perl", but some people have interpreted this to mean
    there's a language called "perl5", which isn't the case. Perl5 is merely
    the popular name for the fifth major release (October 1994), while perl4
    was the fourth major release (March 1991). There was also a perl1 (in
    January 1988), a perl2 (June 1988), and a perl3 (October 1989).

    The 5.0 release is, essentially, a ground-up rewrite of the original
    perl source code from releases 1 through 4. It has been modularized,
    object-oriented, tweaked, trimmed, and optimized until it almost doesn't
    look like the old code. However, the interface is mostly the same, and
    compatibility with previous releases is very high. See the section on
    "Perl4 to Perl5 Traps" in the perltrap manpage.

    To avoid the "what language is perl5?" confusion, some people prefer to
    simply use "perl" to refer to the latest version of perl and avoid using
    "perl5" altogether. It's not really that big a deal, though.

    See the perlhist manpage for a history of Perl revisions.

- 

Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short.  They represent an important
part of the Usenet tradition.  They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile.  If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Answers to questions about LOTS of stuff, mostly not related to
Perl, can be found by pointing your news client to

    news:news.answers

or to the many thousands of other useful Usenet news groups.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release.  It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.

  AUTHOR AND COPYRIGHT

    Copyright (c) 1997-1999 Tom Christiansen and Nathan
    Torkington.  All rights reserved.

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.

                                                           01.04
-- 
    This space intentionally left blank


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

Date: Fri, 6 Jul 2001 19:57:28 -0500
From: "Enrico Ng" <mail@enricong.com>
Subject: Re: how to read multipart/form-data
Message-Id: <9i5mql$e8c$1@info1.fnal.gov>

I got my script to work but what is stored isnt right.
I think it is because I split the entire buffer via "\n" first to
identify the file part.
I want to try not using CGI.pm and cgi-lib.

also, it "read($file, my $buffer, 1024)", what is in $file.

also, I am forced to run my scripts in TAINT mode, so I have to detaint
the filename.
the problem is that, it endsup filtering everything out eventhough its
just I just have "file_name.jpg"

I use
$filename=~ /^(\w+)$/;
$filename= $1;
where $filename is the inputed filename.
--
--
Enrico Ng <mail@enricong.com>
"Dave Hoover" <redsquirreldesign@yahoo.com> wrote in message
news:812589bb.0107061038.480c77a6@posting.google.com...
> Enrico Ng wrote:
> > How do I read multipart/form-data?
>
> Here is a snippet of code from my Soapbox.pm that uploads a file from
> the client to the server.
>
> ----------------
> sub uploadFile {
> my $s = shift;
>         if ($s->{param}{file} ne "") {
> my $path;
> for ($s->{config}{doc_root}, $s->{config}{article_dir}, $s->{name})
> {
> die "illegal characters in config file" if m|[^a-zA-Z0-9_/\.\-]|;
> /^(.*)$/;
> $path .= $1;
> }
> my $file = $q->param("file");
> open(OUTFILE, ">$path")
> or die "unable to open $s->{config}{article_dir}$s->{name}";
> while (my $bytesread = read($file, my $buffer, 1024)) {
> print OUTFILE $buffer;
> }
> close(OUTFILE);
>         } elsif ($s->{param}{type} =~ /cr/i) {
> print "Error: no file selected.";
> }
> }
> ---------------
>
> To see the rest of Soapbox.pm, go here:
> http://redsquirreldesign.com/soapbox/Soapbox.pm.txt
>
> To get more info about Soapbox, go here:
> http://www.redsquirreldesign.com/soapbox
>
> HTH
>
> --
> Dave Hoover
> "Twice blessed is help unlooked for." --Tolkien
> http://www.redsquirreldesign.com/dave




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

Date: Sat, 07 Jul 2001 00:23:01 GMT
From: "Daniel Berger" <djberg96@hotmail.com>
Subject: Re: MySQL,DBI doesn't like my 'LIKE' query
Message-Id: <FDs17.1464$GI4.161773@typhoon.mn.mediaone.net>

<stuff about problems with mysql>

Experience has taught me that whenever DBI/DBD doesn't like a query, it's
something about the way I formed my sql statement.  I curse Oracle and blame
it on a random selection of Oracle environment variables anyway, just for
good measure.

> #!/usr/local/bin/perl
>
> my $query .= "select id from users where description like \'%perl%\' ;
> ";

This looks like the problem.  Try getting rid of that trailing semicolon.
You shouldn't need to escape the single quotes either.  See what happens.

<snip>

> $sth = $dbh->prepare($query) or die "Cant prepare $statement:

Looks like some stuff was either left off or chopped off on this line.  No
trailing quotes or semicolon.

<snip, snip>

99 times out of a 100, if a sql statement fails in the 'prepare()' method,
you've got a sql syntax error somewhere.  The odds of it being a MySql
problem are remote.  I'm not even sure what the 100th time would be, but
there probably is one.

Hope that helps.

Dan








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

Date: Fri, 06 Jul 2001 23:33:01 GMT
From: Darren Dunham <ddunham@redwood.taos.com>
Subject: problem with data..
Message-Id: <NUr17.152790$qv3.42719635@nnrp5-w.sbc.net>

I've written a simplistic client/server program that tars up some files
and sends them over an ssh connection.  It works most of the time, but
since I started testing it, I'm getting corrupted tar files out the
other end some times.  Once, I noticed that the last file in the archive
had some data out of place, not just truncated.

I'd like to know if anyone can see that what I'm doing is a fault of my
perl calls or ssh or something...

The client does this...

   my $cmd = "tar cf - .";
   print "$version\n";
   print `$cmd`;

$version is just a text string to help the server validate the data.

The server opens a filehandle by calling ssh to client with a pipe. 

    my $cmd = "$ssh -e none -n ${user}\@${host} $remote_cmd 2>&1";
    unless (open (SSH, "$cmd|"))
      {
        warn "$0: Could not open ssh connection to $host.\n";
          ...

And then the main thing in the open is..

    my $version = <SSH>;
    # ... section that validates the versioin string
    # ...

    $cmd = "$tar xf -";
    open (TAR, "|$cmd");

    # read from SSH and push to TAR...
    my $buf;
    my $blocksize = "16384";
    my $len;
    while ($len = read SSH, $buf, $blocksize)
      {
        if (!defined $len)
          {
            # whoops, some error occured.
            warn "$0: read error occured: $!\n";
            warn "$0: Skipping host $host.\n";
            close (TAR);
            close(SSH);
            next HOST;
          }
        print TAR $buf;
      }
    close (SSH);
    if ($?)
      { warn "$0: Status from SSH close was $?: $!\n"; }
    close(TAR);
    if ($?)
      { warn "$0: Status from TAR close was $?: $!\n"; }

Because I wanted to quickly grab the version string off the front of the
stream, I'm using <>, read, and print rather than sysread and syswrite.
It could be a little slower, but nothing should get out of order or
truncated if I read it right..

When I run this, I sometimes get errors on a single host like this..

running for calvin...
tar: directory checksum error
infoserver.pl: Status from TAR close was 512:
running for hobbes...
running for homer...

Anyone see what (if anything) I've done wrong here?  It smells like I'm
truncating a buffer or not flushing something, but I don't see where
that might be happening.  

Thanks!

-- 
Darren Dunham                                           ddunham@taos.com
Unix System Administrator                    Taos - The SysAdmin Company
Got some Dr Pepper?                           San Francisco, CA bay area
          < How are you gentlemen!! Take off every '.SIG'!! >


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

Date: Sat, 07 Jul 2001 00:11:09 GMT
From: "Kerry Shetline" <kerry@shetline.com>
Subject: Problems moving from an Apache server to a Windows server
Message-Id: <xss17.1238$Pf6.1168455@typhoon.ne.mediaone.net>

What kinds of things can crash Perl and not even give you an error message?

I'm considering changing the company I'm using to host my web sites, and I'm
currently experimenting with setting up one of those sites in a temporary
staging area on a new server. My old server is a Unix system running Apache
1.3.12. The new server is Microsoft-IIS 5.0 on Windows 2000.

I didn't expect this to be a completely smooth transition, but it's proving
tougher than I bargained for. Perl scripts that ran just fine on the Apache
server are randomly crashing on the Windows system. Both systems have Perl
5.0, the Windows system specifically uses a version of Perl by Activestate.

When I called the hosting company's tech help, all they could tell me was
that my Perl code seems to be crashing their Perl engine. I'm NOT getting
any error messages back -- I'm simply getting nothing at all. When I invoke
one of my CGIs via a server-side include, and view the resultant source from
a web browser, I see that the <--#exec cgi="my.cgi"--> has been stripped
out, but not replaced with anything at all.

What's weird is that this is all so inconsistent. Sometimes the Perl CGIs
work. Sometimes they don't. Same Perl code, same web pages invoking the Perl
code, but nothing consistent about the results. Maybe it's just by chance,
but it seems like directly accessing the URLs of my CGI scripts will cause
them to start working, and then they'll work for a short time via
server-side includes as well -- only to fail again soon after.

Does any of this sound familiar to anyone out there? If so, do you have any
suggestions for work-arounds or fixes? Please keep in mind that this isn't
my own web server, so my access to testing the server and installing new
server software is limited to non-existent.

-Kerry




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

Date: Sat, 7 Jul 2001 10:33:30 +0930
From: "Wyzelli" <wyzelli@yahoo.com>
Subject: Re: Problems moving from an Apache server to a Windows server
Message-Id: <w8t17.3$ji3.768@vic.nntp.telstra.net>

"Kerry Shetline" <kerry@shetline.com> wrote in message
news:xss17.1238$Pf6.1168455@typhoon.ne.mediaone.net...
> What kinds of things can crash Perl and not even give you an error
message?
>

Badly written code!

If you are having problems with a particular piece of code, the best
solution is to narrow it down to as small as practical instance of something
that still demonstates the same problems and then post that here.

Otherwise it is all guesswork, and my PSI::ESP module is misbehaving today.
:)

There can be other issues with IIS 50, and it is a good idea to ensure that
you have all the latest patches, and the latest Perl from Activestate etc
(5.6.1 is good) etc, but there are likely to be problems generated by things
like file lock or path problems which can't be diagnosed without seeing the
programs.

Wyzelli
--
push@x,$_ for(a..z);push@x,' ';
@z='092018192600131419070417261504171126070002100417'=~/(..)/g;
foreach $y(@z){$_.=$x[$y]}y/jp/JP/;print;




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

Date: Fri, 6 Jul 2001 18:42:26 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Stumped on Text extraction\REGEX problem
Message-Id: <slrn9kcfmi.kka.tadmc@tadmc26.august.net>

Gil Vautour <vautourNO@SPAMunb.ca> wrote:
>
>Here goes...  I have one large text file that contains blocks of text
>which I would like to extract and output to their own files.  Each block
>of text starts with the same pattern of characters and ends with the
>same pattern of characters. Each block also has a unique pattern of
>characters (a word, and I have a list of all the possible words) in the
>first line

>What I can't get my head around is how to read in the file to a While
>loop so that I can find each START and output it, and everything after
>it, up to and including END to a new file called UNIQUENAME for each
>block.  Any suggestions would be a great help.


------------------------------------------
#!/usr/bin/perl -w
use strict;

my $re = join '|', qw/ UNIQUENAME1 UNIQUENAME2 UNIQUENAME3 /;

my $block; # of text
while ( <DATA> ) {
   $block .= $_ if /^START / .. /^END /; # see "Range Operators" in perlop.pod

   if ( /^END / ) {                    # process the accumulated block
      my $fname = $1 if $block =~ /^START.*\b($re)\b/;

      print "$fname:\n$block-----\n";  # your processing here
      $block = '';                     # clear the accumulator
   }
}


__DATA__
START blah blah UNIQUENAME1 blah blah
blah blah
blah blah
END blah blah
blah blah
START bleh bleh UNIQUENAME2 bleh bleh
bleh bleh
bleh bleh
END bleh
START bloh bloh UNIQUENAME3 bloh bloh
bloh bloh
bloh bloh
END bloh
------------------------------------------


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


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

Date: Sat, 07 Jul 2001 00:12:37 GMT
From: Bart Lateur <bart.lateur@skynet.be>
Subject: Re: Stumped on Text extraction\REGEX problem
Message-Id: <0fkckt817167vd1uq3nkv51ru4l778k7pn@4ax.com>

Gil Vautour wrote:

>Here goes...  I have one large text file that contains blocks of text
>which I would like to extract and output to their own files.  Each block
>of text starts with the same pattern of characters and ends with the
>same pattern of characters.

>Simplified:
>
>START blah blah UNIQUENAME1 blah blah
>blah blah
>blah blah
>END blah blah
>blah blah
>START blah blah UNIQUENAME2 blah blah
>blah blah
>blah blah
>END
>...
>etc.
>
>What I can't get my head around is how to read in the file to a While
>loop so that I can find each START and output it, and everything after
>it, up to and including END to a new file called UNIQUENAME for each
>block.  Any suggestions would be a great help.

In short: use the range operator in scalar context.

	while(<>) {
	    i f(/^START / .. /^END$/) {
	        print;
	    }
	}

This will print only the parts from START to END, ignoring the rest.

Now, I can image several ways of detecting if you're on the first or the
last line of the block. For example:

	    i f((my $first = /^START /) .. (my $last = /^END$/)) {

$first will be true on the START line, $last will be true on the END
line.

But alternatively, check out the value that .. returns (docs in perlop).

	    i f(my $no = (/^START / .. /^END$/)) {

It's true, yes, but it is also a number. Think of it as the number of
the line in the block, START line is 1. On the last line, it will end in
"E0".

-- 
	Bart.


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

Date: Fri, 6 Jul 2001 18:08:51 -0400
From: "Ala Qumsieh" <qumsieh@sympatico.ca>
Subject: Re: Using a hash passed by reference inside a function??
Message-Id: <3Aq17.32985$g92.4183402@news20.bellglobal.com>


"Carlos C. Gonzalez" <miscellaneousemail@yahoo.com> wrote in message
news:MPG.15afd4838cbee8d989687@news.edmonton.telusplanet.net...
> Hi ya'll,
>
> How can I use a hash passed by reference (in order to prevent it being
> flattened into a scalar) inside a subroutine?

Did you read perlsub and perlref?

> Say that I have a hash called %h
>
> Say that I pass that hash by a call to a function called contents like
> so:
>
> print contents(\%h);
>
> How do I get the function as listed below to print out the hash passed by
> reference??
>
> sub contents
> {
>   my $hash = @_;

You are assigning an array to a scalar, this effectively assigns the number
of entries in @_ (number of arguments to the subruotine, in this case 1) to
$h. You want:

    my ($hash) = @_;

or

    my $hash = shift;

>   while (($k, $v) = each $hash)

    while (my($k, $v) = each %$hash)

>

>     print "$k -> $v\n"
>   }
> }
>
> Perl tells me that I the argument to each must be a hash and not a
> private variable.

--Ala





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

Date: Fri, 06 Jul 2001 22:22:01 GMT
From: Carlos C. Gonzalez <miscellaneousemail@yahoo.com>
Subject: Re: Using a hash passed by reference inside a function??
Message-Id: <MPG.15afe7b3e6d6a3a398968a@news.edmonton.telusplanet.net>

In article <3Aq17.32985$g92.4183402@news20.bellglobal.com>, 
qumsieh@sympatico.ca says...
> 
> Did you read perlsub and perlref?
> 
I read perlsub a couple of times at least, I bought Learning Perl, and 
have a subscription to O'Reilly's Safari where I have read through most 
of another five books but sometimes as happened when I wrote my question 
I had spent upwards of an hour reading and trying some code to figure out 
how to pass hashes into a function without success.

The problem is that there is such a huge amount of material to read 
through that sometimes it saves me a lot of time to ask questions on the 
newsgroup.  

I didn't know there was a perlref.  I will have to look that one up.

Thanks for your input Ala (and thanks to everyone else too). 

---
Carlos
www.internetsuccess.ca


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

Date: Fri, 6 Jul 2001 18:52:20 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Using a hash passed by reference inside a function??
Message-Id: <slrn9kcg94.kka.tadmc@tadmc26.august.net>

Carlos C. Gonzalez <miscellaneousemail@yahoo.com> wrote:
>
>How can I use a hash passed by reference (in order to prevent it being 
>flattened into a scalar) inside a subroutine?


Huh? A reference _is_ a scalar. What "flattening" are you referring to?


>Say that I pass that hash by a call to a function called contents like 
>so:
>
>print contents(\%h);


You want to print() the return value from the contents() subroutine?

Looks to me like your subroutine does all of the necessary printing...


>How do I get the function as listed below to print out the hash passed by 
>reference??
>
>sub contents
>{
>  my $hash = @_;


Problem 1) $hash does not contain a reference to a hash. It contains
           the number of arguments passed to the subroutine.

     my($hash) = @_;     # preferred
or
     my $hash = shift;
or
     my $hash = $_[0];


>  while (($k, $v) = each $hash)


Problem 2) you need to dereference the reference if you want to
get what it is referring to:

     while ( my($k, $v) = each %$hash)
or
     while ( my($k, $v) = each %{$hash})


You need to read up a bit on Perl's references:

   perldoc perlreftut
   perldoc perlref


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


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

Date: Sat, 07 Jul 2001 00:02:33 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: Using a hash passed by reference inside a function??
Message-Id: <3B4651DF.9D7BE984@acm.org>

"Carlos C. Gonzalez" wrote:
> 
> Hi ya'll,
> 
> How can I use a hash passed by reference (in order to prevent it being
> flattened into a scalar) inside a subroutine?
> 
> Say that I have a hash called %h
> 
> Say that I pass that hash by a call to a function called contents like
> so:
> 
> print contents(\%h);
> 
> How do I get the function as listed below to print out the hash passed by
> reference??
> 
> sub contents
> {
>   my $hash = @_;
>   while (($k, $v) = each $hash)
>   {
>     print "$k -> $v\n"
>   }
> }

On the other hand, if you just want to print out a hash:

print map { $a++ % 2 ? "$_\n" : "$_ -> " } %hash;



John
-- 
use Perl;
program
fulfillment


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

Date: Sat, 07 Jul 2001 01:47:53 +0200
From: Buggs <buggs-clpm@splashground.de>
Subject: Re: web fetching
Message-Id: <9i5ind$fug$02$1@news.t-online.com>

Bart Lateur wrote:

> Buggs wrote:
> 
>>I'd be interested in code
>>which tries to achieve that
>>in "plain" Perl without using Socket.
> 
> Run to the book store and get yourself a copy of Lincoln Stein's book
> "Network programming with Perl". All of your questions will be answered
> in that book.

Having a copy I say that it will not explain how
"to achieve that in "plain" Perl without using Socket."

> 
> There should be far more books like this one.
> 

Yup.


Buggs


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

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


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