[19330] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 1525 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Aug 14 21:05:41 2001

Date: Tue, 14 Aug 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: <997837508-v10-i1525@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Tue, 14 Aug 2001     Volume: 10 Number: 1525

Today's topics:
    Re: 2 dimensional array suntax help, please (Tad McClellan)
    Re: 2 dimensional array suntax help, please (Stan Brown)
    Re: 2 dimensional array suntax help, please (Stan Brown)
    Re: Another string manipulation question <goldbb2@earthlink.net>
    Re: behavior in a while loop <ren@tivoli.com>
        FAQ: How do I randomly update a binary file? <faq@denver.pm.org>
    Re: Format error?? (Tad McClellan)
    Re: grep 5th word in a text-file <monty@primenet.com>
    Re: Grep Implemented in Perl <noway@nohow.com>
    Re: IF $FileArray[$index] CONTAINS..... <goldbb2@earthlink.net>
    Re: Intermittent problems printing from perl <goldbb2@earthlink.net>
    Re: modules and variables (Tad McClellan)
    Re: mresolv2 and sockets on HP-UX 10.20 <goldbb2@earthlink.net>
        Nmake.exe error after generating makefile <ronnie@r-davies.demon.co.uk>
    Re: Not inserting duplicate elements into an array (Tad McClellan)
    Re: Not inserting duplicate elements into an array <mdufault@hotmail.com>
    Re: Not inserting duplicate elements into an array <Pcmann1@btinternet.com>
    Re: one character at a time (Ken)
    Re: print to e-mail, good solution wanted (Michael Mauch)
    Re: Sorting Hash of Arrays (Malcolm Dew-Jones)
    Re: Timed out if no input <goldbb2@earthlink.net>
    Re: validate IP address <mdufault@hotmail.com>
        Zapping a DB_File hash? <miscellaneousemail@yahoo.com>
    Re: Zapping a DB_File hash? (Tad McClellan)
    Re: Zapping a DB_File hash? <miscellaneousemail@yahoo.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Tue, 14 Aug 2001 17:09:19 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: 2 dimensional array suntax help, please
Message-Id: <slrn9nj4rv.bb9.tadmc@tadmc26.august.net>

Stan Brown <stanb@panix.com> wrote:
>In <m3zo925ven.fsf@dhcp9-161.support.tivoli.com> Ren Maddox <ren@tivoli.com> writes:
>

>>So get_foreign_key_values() returns a list (the contents of @rval) in
>>list context, or a scalar (the number of elements in @rval, in this
>>case, 2) in scalar context.
>
>Ah, here goes my C bacground again, getting me in trouble. I did not
>realize that a subroutine could return different values, based upon how it
>was called. That partly explains why I have been going in circles all day!


You simply _must_ get the "list context vs. scalar context"
thing down, or you will never "get" Perl.

Notice that nearly all of Perl's functions have a paragraph that says:

   In list context <description of behavior>

and another that says

   In scalar context <description of a *different* behavior>

You cannot know what behavior to expect from Perl's functions
if you do not know what context they are being called in.

See the "Context" section in:

   perldoc perldata



"Context" is a manifestation of Perl's "natural languageness":

   http://www.wall.org/~larry/natural.html


Natural language has "singular" and "plural" contexts.

Perl has "scalar" and "list" contexts.


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


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

Date: 14 Aug 2001 19:29:00 -0400
From: stanb@panix.com (Stan Brown)
Subject: Re: 2 dimensional array suntax help, please
Message-Id: <9lcc7s$f2h$1@panix1.panix.com>

In <slrn9nj4rv.bb9.tadmc@tadmc26.august.net> tadmc@augustmail.com (Tad McClellan) writes:

>Stan Brown <stanb@panix.com> wrote:
>>In <m3zo925ven.fsf@dhcp9-161.support.tivoli.com> Ren Maddox <ren@tivoli.com> writes:
>>

>>>So get_foreign_key_values() returns a list (the contents of @rval) in
>>>list context, or a scalar (the number of elements in @rval, in this
>>>case, 2) in scalar context.
>>
>>Ah, here goes my C bacground again, getting me in trouble. I did not
>>realize that a subroutine could return different values, based upon how it
>>was called. That partly explains why I have been going in circles all day!


>You simply _must_ get the "list context vs. scalar context"
>thing down, or you will never "get" Perl.

I'm begining to understand that.

>Notice that nearly all of Perl's functions have a paragraph that says:

>   In list context <description of behavior>

>and another that says

>   In scalar context <description of a *different* behavior>

>You cannot know what behavior to expect from Perl's functions
>if you do not know what context they are being called in.

Yes, however, I had not made the leap to expecting user defined subroutines
to have similar semantics. I was enviosioning this glorious "object
oreinted world" for the built in functions, so that they could exhibit this
behavior.

I have learned something, thanks to all th helpful people that hang out
here.

>See the "Context" section in:

>   perldoc perldata



>"Context" is a manifestation of Perl's "natural languageness":

>   http://www.wall.org/~larry/natural.html


>Natural language has "singular" and "plural" contexts.

>Perl has "scalar" and "list" contexts.


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


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

Date: 14 Aug 2001 19:35:43 -0400
From: stanb@panix.com (Stan Brown)
Subject: Re: 2 dimensional array suntax help, please
Message-Id: <9lcckf$fk7$1@panix1.panix.com>

In <3B79A1D7.A7AED971@earthlink.net> Benjamin Goldberg <goldbb2@earthlink.net> writes:

>Stan Brown wrote:
>> 
>> Just as I thought I was getting a handle on this, I have managed to
>> confuse myself again :-(
>> 
>> I have a subroutine I call that creates and array of refeences to
>> arrays.  The relevant bits look like this:
>> 
>> my @rval = undef ;

>This creates a one element array, whose value is (undef).  You should
>either not be initializing, or initializing using ();

>my @rval;
>or
>my @rval = ();

Yes, I have already been corected on that, thnaks though.

>> $rc = $sths->execute or die $DBI::errstr;
>> my $row = 0;
>> my $col = 0;
>> while ( @extracted_data = $sths->fetchrow_array ) {
>>     for ($col = 0; $col < $col_qty; $col++) {
>>     $rval[$col][$row] = $extracted_data[$col];
>>     print_debug(5,"Added $extracted_data[$col] to [$row][$col]\n",0);
>>     }
>>     $row++;
>> }
>> 
>> return @rval;

>sub get_foreign_key_values {
>	my ($table, $cols);
>	local $dbi->{RaiseError} = 1;
>	local $" = ", ";
>	my $sth = $dbi->prepare("SELECT @$cols FROM $table");
>	$sths->execute();
>	my @rval;
>	while( my $onerow = $sths->fetchrow_arrayref ) {
>		for my $col ( 0 .. $#$onerow ) {
>			push @{$rval[$col]} => $onerow->[$col];
>			print_debug(5, "Added $$onerow[$col] to " .
>				"[$col][$#{$rval[$col]}]\n", 0);
>		}
>	}
>	return wantarray ? @rval : \@rval;
>}

>This returns a reference to the array if called in scalar context, or an
>list if called in list context.

Oh, cool! I have now learned not only that user defined subroutines can,
and do return diferent things in diferent contexts, but that I can program
in specific behavior based upon the context my subroutines are called in.

>> All of this _seems_ br working corectly. The trouble arises in using
>> it.
>> Like this:
>> 
>> my $vals = get_foreign_key_values(
>>                 $$hash_pointer{$col}{'SRC_TABLE'},
>>                 $$hash_pointer{$col}{'SRC_COLS'});

>Since your get_foreign_key_values always tries to return an array,
>regardless of it's context, $vals ends up with the number of elements of
>that array, not it's contents.  In other words, it's likely going to end
>up as "2" or somesuch.

I should have seen that sooner. I was thinking that the "2" was one of the
values in the array, however, I should have recognized that here were no
"2"'s in the dataset.

This was confusing the ** out of me!

>> $entry->insert(0,$$vals[0]);

>insert wants a list.  $$vals[0] starts with a $ which means it's a
>scalar.  For that matter, it's taking "$vals" using it as a reference to
>an array, and since $vals is 2, this line is essentially like saying:
>	$entry->insert(0, ${'2'}[0]);

>So either:
>my $vals = ... # with my code, which returns \@vals in scalar context.
>$entry->insert(0, @{$vals->[0]} );
>or
>my @vals = ...# with either my or your code.
>$entry->insert(0, @{$vals[0]} );

>By the way, are you *sure* entry takes a list, not a reference to a
>list?

Mmm, it seems to be working thta way. Actually in the doc's it says it
takes a scalar, but I already had it working with an array, which I was
using as a prototype for this code.

Thanks for the help!


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

Date: Tue, 14 Aug 2001 18:31:40 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Another string manipulation question
Message-Id: <3B79A6CC.B6E5A408@earthlink.net>

Doug Robbins wrote:
> 
> I have a string like this (for example) whic a perl script is getting
> from a generated text file:
> 
> 03:00 PM EST
> 
> Problem is, the hour is off by one hour (slow). Hour can I increment
> the hour by one? In other words, when the original string contains
> 03:00 I want 04:00, when its 06:00 I want 07:00, etc. Get's trickier
> when we get to 12:00...
> 
> Of course I could simply replace 'EST' with 'CST' but that would be
> too easy :)

my $timestr = "03:00 PM EST";
my $adjust = 60;
my ($hh,$mm,$meridian,$tz) = $datestr =~ m[(\d\d):(\d\d) (..) (.*)];
my $time = $hh*60 + $mm + $meridian*12*60 + $adjust;
my $timenew = sprintf("%02d:%02d %s %s",
	($time/60-1)%12+1, $time%60,
	($time/60)%24 < 12 ? "AM" : "PM", $tz);

-- 
The Swedish Chef has been assimilated. "Borg borg borg!"


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

Date: 14 Aug 2001 16:01:24 -0500
From: Ren Maddox <ren@tivoli.com>
Subject: Re: behavior in a while loop
Message-Id: <m3r8ue5paz.fsf@dhcp9-161.support.tivoli.com>

On 14 Aug 2001, c_barbet@hotmail.com wrote:

> Hello!  I am looking for code that reads from a text file the name
> of files to be moved and moves them.  The code I included works
> *HOWEVER* there is a problem.  If the directory being searched is
> empty it then moves the file associated with FSN_LIST.  Why?  ***
> this is the important question.

If the directory is empty, what's in the file?  What populates the
file?  Is it possible that the problem is in the code that builds the
file instead of this code?  (Hint: Yes.)

> I do have an easy second question(yes I be a perl newbie).  What is
> considered proper syntax using the keyword 'or' or '||' when working
> with filehandles.  I read a bit on precedence (camel head), and
> recommended was the literal 'or' however I see many people using the
> logical operator (???)

It depends.  I prefer "or" for flow control and "||" for logical
comparisons.  If you use them that way, you will almost never have a
problem.  If you use them differently than that, you will
occasionally run into a precedence problem -- unless you are always
very aware of precedence issues.

> thanks in advance
> 
> ---- almost good code ---- 
> open(FSN_LIST, "./fromscan.lst") or die ERROR_LOG, "\nCould not read
> ./fromscan.lst: $!";
> while (<FSN_LIST>) {
>     print "I passed this file: $_"; #just to make sure we see a

You didn't say whether or not this line printed.  Presumably, the file
is empty so we never actually enter this while loop.  But if that were
really true...

>     file.  chomp($_); #get rid of that newline
>     rename("$fsndir/$_", "./fsn/$_") || die ERROR_LOG, "\nCould not
> copy $_: $!";

 ... then the rename would not be executed either, and you wouldn't
have had a problem.

> }
> 
> #code below is original code, code above was done for TESTING some
> theories.
> #they perform the same exact function with the same exact weirdness.
> 
> #while ($fileFSNL = <FSN_LIST>) {
> #    print "I passed this file: $fileFSNL"; #just to make sure we see
> a file.
> #    chomp($fileFSNL);
> #    rename("$fsndir/$fileFSNL", "./fsn/$fileFSNL") or die ERROR_LOG,
> "\nCould not copy $fileFSNL: $!";
> #}

Ditto.  The problem is elsewhere.

-- 
Ren Maddox
ren@tivoli.com


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

Date: Wed, 15 Aug 2001 00:17:06 GMT
From: PerlFAQ Server <faq@denver.pm.org>
Subject: FAQ: How do I randomly update a binary file?
Message-Id: <6cje7.102$V3.170992640@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.

+
  How do I randomly update a binary file?

    If you're just trying to patch a binary, in many cases something as
    simple as this works:

        perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs

    However, if you have fixed sized records, then you might do something
    more like this:

        $RECSIZE = 220; # size of record, in bytes
        $recno   = 37;  # which record to update
        open(FH, "+<somewhere") || die "can't update somewhere: $!";
        seek(FH, $recno * $RECSIZE, 0);
        read(FH, $record, $RECSIZE) == $RECSIZE || die "can't read record $recno: $!";
        # munge the record
        seek(FH, -$RECSIZE, 1);
        print FH $record;
        close FH;

    Locking and error checking are left as an exercise for the reader. Don't
    forget them or you'll be quite sorry.

- 

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.

                                                           05.20
-- 
    This space intentionally left blank


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

Date: Tue, 14 Aug 2001 17:13:05 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Format error??
Message-Id: <slrn9nj531.bb9.tadmc@tadmc26.august.net>

Carlos C. Gonzalez <miscellaneousemail@yahoo.com> wrote:
>In article <slrn9nieck.9os.tadmc@tadmc26.august.net>, Tad McClellan at 
>tadmc@augustmail.com says...
>
>> I haven't used "format" for years. printf() and a word-wrapping
>> module do it for me.
>
>Which module do you use Tad? 


I've been using Text::Wrap, but plan to use Damian's
Text::Autoformat the next time I need one.


>> formats will be removed from the core in perl6.
>> 
>> The payback you get for learning them is not worth the trouble, IMO.
>
>Makes sense.  Now that I know they are being removed in Perl6 I will 
>definitely get away from using them.


They will be available as a module in Perl 6, I believe.


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


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

Date: 14 Aug 2001 22:45:15 GMT
From: Jim Monty <monty@primenet.com>
Subject: Re: grep 5th word in a text-file
Message-Id: <9lc9lr$5i9$1@nnrp1.phx.gblx.net>

Rafael Garcia-Suarez <rgarciasuarez@free.fr> wrote:
> Timo Trinks wrote in comp.lang.perl.misc:
> > i'm trying to code a script that reads the 5th word of a line and writes
> > it to stdout:
> [...]
> > i tried sth like my $word = (split ' ', $1)[4]; but unsuccessfully...
> > so any ideas ?
>
> You've made a mistake; replace $1 by $_ or by whatever variable holds
> the current line.
>
> Here's the one-line version :
>     perl -lne 'print((split)[4])' file

*The* one-line version?

    $ echo 'radius log report for: foo' |
    > cut -f 5 -d ' '
    foo
    $ echo 'radius log report for: foo' |
    > egrep '^radius log report for:' | cut -f 5 -d ' '
    foo
    $ echo 'radius log report for: foo' |
    > awk '{ print $5 }'
    foo
    $ echo 'radius log report for: foo' |
    > awk '/^radius log report for:/ { print $5 }'
    foo
    $ echo 'radius log report for: foo' |
    > perl -lane 'print $F[4]'
    foo
    $ echo 'radius log report for: foo' |
    > perl -lane 'print $F[4] if m/^radius log report for:/'
    foo
    $

-- 
Jim Monty
monty@primenet.com
Tempe, Arizona USA


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

Date: Wed, 15 Aug 2001 00:06:24 GMT
From: "Buck Turgidson" <noway@nohow.com>
Subject: Re: Grep Implemented in Perl
Message-Id: <42je7.117220$J37.28951732@typhoon.southeast.rr.com>

I think the PPT version is the one I am looking for.

I see the -r flag, to process an entire directory.  Any idea how to
do, say "*.sql" within a directory?

usage: \uf\perl\tcgrep.pl [flags] [files]

Standard grep options:
        i   case insensitive
        n   number lines
        c   give count of lines matching
        C   ditto, but >1 match per line possible
        w   word boundaries only
        s   silent mode
        x   exact matches only
        v   invert search sense (lines that DON'T match)
        h   hide filenames
        e   expression (for exprs beginning with -)
        f   file with expressions
        l   list filenames matching
        F   search for fixed strings (disable regular expressions)

Specials:
        1   1 match per file
        H   highlight matches
        u   underline matches
        r   recursive on directories or dot if none
        t   process directories in `ls -t` order
        p   paragraph mode (default: line mode)
        P   ditto, but specify separator, e.g. -P '%%\n'
        a   all files, not just plain text files
        q   quiet about failed file and dir opens
        T   trace files as opened

May use a TCGREP environment variable to set default options.





"Tad McClellan" <tadmc@augustmail.com> wrote in message
news:slrn9nigt9.a1l.tadmc@tadmc26.august.net...
> Buck Turgidson <jc_va@hotmail.com> wrote:
>
> >Can someone point me to a good version of grep written in Perl
> >somewhere?
>
>
> Here's "grep -h":
>
>    perl -ne 'print if /PATTERN/' filenames...
>
>
> Here's "grep -H":
>
>    perl -ne 'print qq($ARGV: $_) if /PATTERN/' filenames...
>
>
> Then there's always the Perl Power Tools project:
>
>    http://language.perl.com/ppt/src/grep/index.html
>
>
> --
>     Tad McClellan                          SGML consulting
>     tadmc@augustmail.com                   Perl programming
>     Fort Worth, Texas




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

Date: Tue, 14 Aug 2001 18:19:58 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: IF $FileArray[$index] CONTAINS.....
Message-Id: <3B79A40E.ABA0726F@earthlink.net>

Pete Sohi wrote:
> 
> Saviours and brave developers alike:
> 
> I am a Java (and ABAP) developer out of my normal territory and find
> myself wrestling with Perl for the first time.
> 
> I have an array containing scalars (filenames [strings]) and want to
> traverse it searching for filenames which CONTAIN x char sequence....
> 
> The conditions being CONTAINS. (I would have expected a nice keyword
> like EXISTS or CS [as it is in ABAP] but there isnt one)

my @x = qw(foo bar blah ick);
my $x = "b"; # all words with "b" anywhere in them
my @y = grep { index($_,$x) != -1 } @y;
my @z = grep /$x/, @y; # also works, but uses $x as a regular expression

Also, you don't need to store the intermediate results anywhere:
foreach my $matched_word ( grep /$x/, @y ) {
	# do something with $matched_word
}
or even:
foreach my $matched ( grep /$x/, qw(foo bar blah ick) ) {
	# do something with $matched
}

-- 
The Swedish Chef has been assimilated. "Borg borg borg!"


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

Date: Tue, 14 Aug 2001 19:21:43 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Intermittent problems printing from perl
Message-Id: <3B79B287.96227973@earthlink.net>

Zenon Bachir wrote:
> 
> Hello,
> 
> I am getting an intermittent problem trying to print a postscript
> file. I have a perl batch program which runs automatically from a
> scheduler. It logs onto our Oracle database and checks a queue for
> pending jobs. It then calls our report generator (SQR) which creates a
> postscript file. It tries to print the file using the &#8216;lp&#8217;
> command. If all goes well it removes the job from the queue.
> 
> It seems that sometimes (30% of the time) the file does not print!
> There is no error. It just quietly goes on its way. The postscript
> file looks OK. I can view/print it with no problems.
> 
> Is it possible that the postscript file does not yet exist when we try
> to print? Is checking for the return from &#8216;system&#8217; enough
> to detect any problems that occurred?

It's possible... what does sqr do?  Does it return instantly, doing it's
work in the background, or does it block until it's done [and the
postscript file is created]?

> Any help would be appreciated.

I think your sequence of if() blocks is a bit confused.  If I were you,
I would try to keep nesting to a minimal, and do my if() tests on the
return values of system directly.  Also, I don't see the point in
putting everything together into string and passing to system, when you
would be better off passing a list to system.

	use strict;
	unless( system "sqr", $SQR_REPORT_DIRECTORY . 'request.sqr',
		$ORACLE_SQR_USER . '@' . $DB_MACHINE,
		$requestId, $cpdRoomId, "-e", "-PRINTER:PS",
		"-F$outFile", "-E$errFile" )
	{
	         process_error "ERROR could not create report: ",
			 "\$? is $?, \$! is $!\n";
		exit 1;
	}
	unless( my $printerQueue = get_printer ($cpdRoomId) ) {
		process_error "Invalid printer: $printerQueue " .
			"for Compound Room $cpdRoomId\n";
		exit 1;
        }
	unless( system( "lp", "-d", $printerQueue, $outFile ) ) {
		print STDERR "Failed to send $outfile to printer ",
			"$printerQueue: \$? = $?, \$! = $!\n";
		exit 1;
	} else {
		print "$outfile sent to printer $printerQueue\n";
	}
	unless( $dbi->do( "GCIS.JOBS_API.REMOVE(?)", undef, $jobId ) )
	{
		print STDERR "Could not remove job $jobId: " .
			"$DBI::err --- $DBI::errstr\n";
		exit 1;
	} else {
		print "REMOVE FROM QUEUE... job_id = $job_id\n";
	}

Oh, and I found your error.

      $sqrString = 'lp -d ' . $printerQueue . ' '. $outFile;
      print "PRINTING... ". $printerCommand . "\n";
      
        sleep 2; # desperation
        $sysRet = system($printerCommand);

You create a printer command and put it in $sqrString, but you don't
pass $sqrString to system, you pass $printerCommand !

If you'd given the arguments to system() directly, rather than storing
them in a variable and then passing that variable to system(), this
would never have happened.

If you'd used "strict" you might have caught this... you almost
certainly would have caught it if you had checked the results of the
system command immediately after you'd called it, and seen that the
system() call which was supposed to be "lp" never succeeded.

Hmm, or if you'd used Larry Wall's funky Shell.pm, as in:
	use Shell qw(sqr lp);
	unless( defined lp( "-d", $printerQueue, $outFile ) ) {
		...
	}

-- 
The Swedish Chef has been assimilated. "Borg borg borg!"


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

Date: Tue, 14 Aug 2001 17:18:39 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: modules and variables
Message-Id: <slrn9nj5df.bb9.tadmc@tadmc26.august.net>

gnari <gnarinn@hotmail.com> wrote:
>In article <3B8276D5.51A6DB30@sprintmail.com>,
>Jeff Thies  <cyberjeff@sprintmail.com> wrote:
>>  I have a few functions that I've moved into a module. I'm unsure how
>>to initialize/reset global variables for these functions. 
>>
>>  Here's what I have:
>>
>>use myModule($enviornment_var1,$enviornment_var2);
>
>the list after the 'use myModule' is the import list and are not some
>sort of arguments passed to your module


And on top of that, "use" happens at compile time.

$enviornment_var1 is likely assigned a value at runtime, so
it is uninitialized at compile time, when the "use" happens.


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


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

Date: Tue, 14 Aug 2001 20:06:02 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: mresolv2 and sockets on HP-UX 10.20
Message-Id: <3B79BCEA.421822E5@earthlink.net>

Mike wrote:
> 
> <originally posted in comp.lang.perl by mistake>
> 
> Hello all,
> 
> I've been using Perl for a few years, but never sockets (in any
> language) until now.  I'm trying to get a script given to me working
> under HP-UX 10.20 and Perl 5.005_02 (our current in-house production
> version - upgrading is not an option right now unless really needed)
> which was based on mresolv2 1.3 (http://www.fuhr.org/~mfuhr/perldns/).
>  When the script runs, the socket bind fails with an "Invalid
> argument".  So, I thought, since the script is based on mresolv2, let
> me try the original, unchanged mresolv 1.3.  I did, and I get the same
> thing, an "Invalid argument", specifically:
> 
> can't bind socket: Invalid argument at mresolv2.pl line 58.
> 
> After hunting in the newsgroup archives at groups.google.com, I tried
> changing the source address to a specific interface's address (instead
> of 0.0.0.0), and the source port to a specific non-priv port (instead
> of 0), but this did not change the result.
> 
> I know general (non-IO) socket support is correctly installed because
> I tried the simple UDP example in the perlipc manpage and it returns
> what I think is the proper result (time difference between local
> machine and each host on the network which I supply on the command
> line).
> 
> What (probably obvious) thing am I missing?  I suspect it's something
> obvious because if I really knew socket programming I think it would
> jump out at me.

Maybe rewriting it like this will help?

my $sock = IO::Socket::INET->new(
	Proto => "udp",
	PeerPort => DEFAULT_PORT,
	PeerAddr => $res->nameservers ?
		($res->nameservers)[0] : $default_nameserver,
	LocalPort => DEFAULT_SRCPORT,
	LocalAddr => DEFAULT_SRCADDR,
) or die "Can't create bound socket: $!";

Whether doing the bind in the constructor, rather than later, will help,
I don't know.  But it's easyer on the eyes, anyway.

Also, consider using it as originally posted:
	http://groups.google.com/groups?oi=djq&selm=an_455581292

-- 
The Swedish Chef has been assimilated. "Borg borg borg!"


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

Date: Tue, 14 Aug 2001 23:25:07 +0100
From: Ronnie Davies <ronnie@r-davies.demon.co.uk>
Subject: Nmake.exe error after generating makefile
Message-Id: <jyiRvGADVae7Ewi$@r-davies.demon.co.uk>

I am running Windows 98 and have read about problems with the 2>&1
string in mm_win32 and mm_unix when compiling makefile.pl.  I am trying
to install the Borland Interbase 6 DBD.

By removing the 2>&1 string from mm_win32 and one from mm_unix, I have
made a makefile without any errors being thrown up.  However, I still
get the following output when running nmake directly after generating
makefile:-

        c:\perl\bin\perl.exe -p -e "s/~DRIVER~/InterBase/g" <
C:/Perl/site/lib/a
uto/DBI/Driver.xst > InterBase.xsi
File not found
        c:\perl\bin\perl.exe -IC:\Perl\lib -IC:\Perl\lib
C:\Perl\lib\ExtUtils/xs
ubpp   -typemap C:\Perl\lib\ExtUtils\typemap InterBase.xs > InterBase.c
Cannot open 'InterBase.xsi': No such file or directory in InterBase.xs,
line 19
NMAKE : fatal error U1077: 'C:\PERL\BIN\PERL.EXE' : return code '0x1'
Stop.

How do I get nmake to work without errors?  I really need to get this
DBD installed!

Thanks in advance
-- 
Ronnie Davies

He who laughs last........thinks slowest!


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

Date: Tue, 14 Aug 2001 17:20:55 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Not inserting duplicate elements into an array
Message-Id: <slrn9nj5hn.bb9.tadmc@tadmc26.august.net>

Peter Mann <Pcmann1@btinternet.com> wrote:

>  I am having a problem determining how to populate an array, but if an
>element already exists in the array then not insert the same element again!


Perl FAQ, part 4:

   "How can I remove duplicate elements from a list or array?"


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


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

Date: Tue, 14 Aug 2001 23:03:54 GMT
From: "Mark W. Dufault" <mdufault@hotmail.com>
Subject: Re: Not inserting duplicate elements into an array
Message-Id: <u7ie7.249414$v5.25738137@news1.rdc1.ct.home.com>

Sort the array then check the next element and if it is the same skip it...
############################################################################
##
# Arguments: A sorted Array
# Returns: Array with duplicates removed
############################################################################
##
sub unique {
     my @unique ;
     for (my $i = 0; ($i < $#_); $i++) {
          if ($_[$i] =~ $_[$i + 1]) { next ; }
          push  (@unique, $_[$i]) ;
     }
 return @unique ;
}

@output = unique (@input) ;

"Jürgen Exner" <jurgenex@hotmail.com> wrote in message
news:3b7989eb$1@news.microsoft.com...
> "Peter Mann" <Pcmann1@btinternet.com> wrote in message
> news:9lc0qd$lv0$1@plutonium.btinternet.com...
> > Dear All,
> >   I am having a problem determining how to populate an array, but if an
> > element already exists in the array then not insert the same element
> again!
> [...]
> > So how do I ensure duplicate links are not inserted into the array?
>
> Can you use a hash (actually the keys of a hash) instead of an array?
> When you need an array just do "keys %myhash" and you got an array of all
> the values you added. Of course this will not preserve the sequence used
to
> enter the values.
>
> jue
>
>




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

Date: Wed, 15 Aug 2001 00:07:06 +0100
From: "Peter Mann" <Pcmann1@btinternet.com>
Subject: Re: Not inserting duplicate elements into an array
Message-Id: <9lcat1$apg$1@neptunium.btinternet.com>

Dear all,
Ok, I looked up a Hash in my books and in theory it does what I need.
But im not sure how to code it? A hash needs a value and a key right? But if
I just have a list of links, what would be the key and what would be the
content? The 'url' would effectively be unique, so is this the key?
Anyway, I tried to implement what I think I need, but I cant get it to work.
Does anyone have any suggestions?

  my $page  = new Page $uri;       # Create a new Page object. Call the
constructor
  my $links = $page->links;          # Now extract the links from the page


  my %linksFromPage;                               # Create the hash

  for my $temp (@$links) {                        # Loop through all the
links
    if (exists $linksFromPage{$temp}) {      # If its already in the hash
then next link
      next
    else {                                                     # Else link
doesnt exist, hence add the link to the hash
      $linksFromPage{$uri} = $temp;
    }
  }



Thanks in advance for any help!
  - Pete


"gnari" <gnarinn@hotmail.com> wrote in message
news:997819697.778033625800163.gnarinn@hotmail.com...
> In article <9lc0qd$lv0$1@plutonium.btinternet.com>,
> Peter Mann <Pcmann1@btinternet.com> wrote:
>
> >Dear All,
> >  I am having a problem determining how to populate an array, but if an
> >element already exists in the array then not insert the same element
again!
>
> use a hash
>
> gnari




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

Date: 14 Aug 2001 16:57:59 -0700
From: kenphilbrick@mindspring.com (Ken)
Subject: Re: one character at a time
Message-Id: <f8b445c0.0108141557.97538c@posting.google.com>

Ilya Martynov <ilya@martynov.org> wrote in message news:<87d75ywjou.fsf@abra.ru>...
> K> I have some strings of text that I need to take one character out of
> K> at a time.  I've looked into getc(), but that apparently only works on
> K> filehandles (and according to the Camel book, it's also very slow).
> 
> K> An example of what I need:
> 
> K> I have the string "my little string".  I need to loop through and pull
> K> out first the 'm', then the 'y', then the ' ', then the 'l', etc.
> 
> I'm sure it is not very efficient for very long strings but if you do
> not care you can use following code:
> 
> my $string = "my little string";
> 
> for my $char (split '', $string) {
>     # here you loop through all chars. In each iteration next char is
>     # in variable $char.
> }

Thanks, that's just what I needed.

--
Ken


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

Date: Tue, 14 Aug 2001 22:45:52 +0000
From: michael.mauch@gmx.de (Michael Mauch)
Subject: Re: print to e-mail, good solution wanted
Message-Id: <0n9cl9.dl.ln@elmicha.333200002251-0001.dialin.t-online.de>

Mikko Koljander <koldex@spamcop.net> wrote:
> I did my best trying to select only the most appropriate newsgroups
> for this undeniably quite cross-platform post. If I did any
> technical/conduct mistakes, I apologize - try to focus on the subject,
> not flaming :-)

Then why didn't you set an appropriate Followup-To? Why didn't you use
one of the hundreds of microsoft.* groups?

> The only problem is that I have a need, but not time/skills to make it
> happen.

There's an easy way to have that done: hire somebody who has the time
and skills.

> Has anyone done thing like this already? Any volunteers for
> making this kind of thing under GNU Public License :-) ?

Probably there will be no problem to find someone who can do this and
release it under the GPL. You know the difference between free beer and
free software?

F'up2 poster.


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

Date: 14 Aug 2001 15:35:23 -0800
From: yf110@vtn1.victoria.tc.ca (Malcolm Dew-Jones)
Subject: Re: Sorting Hash of Arrays
Message-Id: <3b79a7ab@news.victoria.tc.ca>

Tad McClellan (tadmc@augustmail.com) wrote:
: Malcolm Dew-Jones <yf110@vtn1.victoria.tc.ca> wrote:
: >Drew Myers (bh_ent@hotmail.com) wrote:
: >: I've gone through this newsgroup, all my Perl books, and asked the few
: >: guys in my office that code in Perl this question, with no real
: >: resolution.
: >
: >: And yes, I read the excellent paper by Larry and Uri regarding Perl
: >: Sorts, but it was a tad over my head.
: >
: >: 1) Is it possible to sort any field of a hash of arrays via the
: >: Schwartzian Transform?


: You can sort arrays. You cannot force a storage order on
: hash keys though.


: >%HoA is a hash.  It isn't possible to sort the keys of a hash, you can
: >only sort elements in an array. 
:                           ^^^^^

: A "list" actually:

Are you saying you can "only sort elements in a *list*". ?  I meant an
array as opposed to a hash - i.e. given a hash and an array, only the
array can be sorted.


: >In the above you might want something like (all untested)
: >
: >     @HoA = sort { $HoA{$a}->[0] <=> $HoA{$b}->[0] }
:                             ^       ^^^       ^
:                             ^       ^^^       ^
: >                 keys %Hoa;


: He wanted descending order, need to swap a/b.

: He wants to compare strings, need "cmp" not "<=>".


Well I did give the caveats "something like" and "(all untested)" to
indicate I had just whipped the code out without checking it over at all,
though I'm sure he will appreciate someone adding these checks, thanks.



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

Date: Tue, 14 Aug 2001 19:35:17 -0400
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Timed out if no input
Message-Id: <3B79B5B5.17CE4182@earthlink.net>

Jim wrote:
> 
> Hi,
> I guess this is simple to do but I'm not having much luck.
> I want to wait 5 seconds for a Y/N ans to a question
> "Do you want to continue? "
> If I get a Y within 5 seconds I print "Continuing" if I
> get a N or nothing the script exits.

sub ask_continue {
	local $| = 1;
	print "Do you want to continue? ";
	vec( my $flags, fileno STDIN, 1 ) = 1;
	if( !select( $flags, undef, undef, 5 ) ) {
		print "[timeout] yes\n";
		return 1;
	}
	return (<STDIN> !~ m/[nN]/);
}

-- 
The Swedish Chef has been assimilated. "Borg borg borg!"


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

Date: Tue, 14 Aug 2001 23:26:23 GMT
From: "Mark W. Dufault" <mdufault@hotmail.com>
Subject: Re: validate IP address
Message-Id: <zsie7.249454$v5.25746164@news1.rdc1.ct.home.com>


IP addresses are difficult to match using a simple regular expression,
because the regular expression must verify that the IP address against which
it is matching is valid. A simple expression such as
/\d{3}\.\d{3}\.\d{3}\.\d{3}/  will incorrectly match strings such as
789.23.2.900, which is outside the range of valid IP addresses (i.e.,
0.0.0.0 to 255.255.255.255). Damian Conway's Regexp::Common
(http://velocity.activestate.com/code/search?query='Regexp::Common') module
provides a very effective regular expression which matches only valid IP
addresses.

Usage

#!/bin/perl
use Regexp::Common;

while(<DATA>) {
  if(/$RE{net}{IPv4}{dec}{-keep}/) {
    print "IP Address: $1\n";
  }
}

__DATA__
24.113.50.245
0.42.523.2
255.242.52.4
2.5.3


"John Stanley" <stanley@skyking.OCE.ORST.EDU> wrote in message
news:9l9b25$264$1@news.orst.edu...
> In article <9knjf5$2ns$1@suaar1aa.prod.compuserve.com>,
> Richard A. Evans <EvR@compuserve.com> wrote:
> >> You're missing that the from xxx.xxx.xxx.xx is not the only valid form
for
> >> ip addresses.
> >
> >I was responding to the comments that said:
> >
> >If you mean valid as in "correct number of numbers", a short regular
> >expression will do the trick:
> >
> >  $ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
> >  # make sure you have four digit sequences 1-3 numbers each, separated
by
> >periods,
> >  # and that the IP takes up the entire variable
>
> 127.1 has "the correct number of numbers". 324156926 has "the correct
> number of numbers".  Any test that results in 127.1 being rejected is
> incorrect.
>




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

Date: Tue, 14 Aug 2001 22:14:26 GMT
From: Carlos C. Gonzalez <miscellaneousemail@yahoo.com>
Subject: Zapping a DB_File hash?
Message-Id: <MPG.15e350b8b0ee9d35989742@news.edmonton.telusplanet.net>

Hi everyone,

I am learning to work with hashes and was wondering if there was some way 
to zap a hash completely? 

If I have a hash tied to a file through DB_File how to do I delete the 
contents of the file (hash) completely so that I can put fresh info in 
it?  Aside from deleting the file itself and then creating a new one?  

I know I can itererate(?) through the hash one key/value pair at a time 
and use the delete() function but is there some quicker way?  A zap or 
pack sort of function?  

I have read all the FAQ's on hashes and have searched and read various 
articles on Google and can find no description of such a function.  

Thanks for any input on this.

-- 
Carlos 
www.internetsuccess.ca 
*NOTE*: Internet Success is NOT yet fully operational 
so although you are welcomed to visit and take a 
look, trying to subscribe will only be a frustration 
for you as your data will not be saved at this time.


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

Date: Tue, 14 Aug 2001 18:08:09 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Zapping a DB_File hash?
Message-Id: <slrn9nj8a9.bh8.tadmc@tadmc26.august.net>

Carlos C. Gonzalez <miscellaneousemail@yahoo.com> wrote:
>
>I am learning to work with hashes and was wondering if there was some way 
>to zap a hash completely? 


   %hash = ();   # empty out the hash, keep its memory in case
                 # you put anything back into it

or

   undef %hash;  # get the memory back for other uses


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


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

Date: Wed, 15 Aug 2001 00:33:19 GMT
From: Carlos C. Gonzalez <miscellaneousemail@yahoo.com>
Subject: Re: Zapping a DB_File hash?
Message-Id: <MPG.15e37156a1636c1d989743@news.edmonton.telusplanet.net>

In article <slrn9nj8a9.bh8.tadmc@tadmc26.august.net>, Tad McClellan at 
tadmc@augustmail.com says...
> Carlos C. Gonzalez <miscellaneousemail@yahoo.com> wrote:
> >
> >I am learning to work with hashes and was wondering if there was some way 
> >to zap a hash completely? 
> 
> 
>    %hash = ();   # empty out the hash, keep its memory in case
>                  # you put anything back into it
> 

When you say keep it's memory I am assuming you mean the memory taken up 
by the hash variable and not by the contents of the hash.  Is this 
assumption correct?  

When you put something back into a hash does Perl dynamically allocate 
increased memory for the contents and then shrink (free) it as you delete 
items from the hash?  Or does a Perl hash just grow and grow and grow 
without it's memory storage ever being dynamically decreased? (leading to 
it being better to read parts of a file into a hash rather than the whole 
thing all at once).  

>    undef %hash;  # get the memory back for other uses

Does undefining a hash release the memory taken up by the hash variable 
as well as that taken up by it's contents.  All in one operation?

Thanks.

-- 
Carlos 
www.internetsuccess.ca 
*NOTE*: Internet Success is NOT yet fully operational 
so although you are welcomed to visit and take a 
look, trying to subscribe will only be a frustration 
for you as your data will not be saved at this time.


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

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


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