[19894] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 2089 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Nov 8 00:05:47 2001

Date: Wed, 7 Nov 2001 21:05:10 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <1005195909-v10-i2089@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Wed, 7 Nov 2001     Volume: 10 Number: 2089

Today's topics:
    Re: Best language for low IQ programmers? (jmburton)
    Re: Can perl open a new browser window without embeddin <rob_13@excite.com>
    Re: DB module to store references? <goldbb2@earthlink.net>
        DBD::Mysql arbitrarily creating duplicate entries (Bill Gerba)
    Re: DBD::Mysql arbitrarily creating duplicate entries (Garry Williams)
    Re: Help: simple perl question on Windows <jeff@vpservices.com>
        How to find length of scalar var? <mmlai@sfu.ca>
    Re: How to find length of scalar var? (Mark Jason Dominus)
    Re: How to find length of scalar var? <tony_curtis32@yahoo.com>
    Re: How to find length of scalar var? <vze34thh@verizon.net>
    Re: How to find length of scalar var? <joe+usenet@sunstarsys.com>
    Re: IO::SOCKET:INET (Garry Williams)
    Re: Is it possible to convert a UNIX shell command into <goldbb2@earthlink.net>
    Re: map question <zak@mighty.co.za>
    Re: map question <bart.lateur@skynet.be>
    Re: Opening/creating files <mgjv@tradingpost.com.au>
    Re: Opening/creating files <vze34thh@verizon.net>
    Re: Opening/creating files <mgjv@tradingpost.com.au>
    Re: Oracle DBI Question <turtle*no-spam*@iislands.com>
        passing array values from perl to javascript  <hugo@fractalgraphics.com.au>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Wed, 7 Nov 2001 21:06:37 -0600
From: jmburton@usenix.org (jmburton)
Subject: Re: Best language for low IQ programmers?
Message-Id: <1005188797788841@usenix.org>

> C++ is the best choice for dull programmers. The quality of your code will
> be indistinguishable from that of a the C++ guru.

Are you a troll?

In case if you are genuine, which I doubt, I disagree. Eiffel is a
better language for dull programmers. Since Eiffel is usually abandoned
before software goes into production, no one will ever have to deal
with the inevitable bugs left by sloppy Eiffel programmers.
Plus, poor performance due to bad algorithms designed by poorly
educated programmers can be excused by the natural slowness of Eiffel
(garbage collection instead of efficient on-demand memory allocation
and deallocation).

You have to know C++ anyway, as Eiffel is merely a front end to C++
(it is compiled into C++, not native code), and requires external calls
to C++ for anything useful like OS services.

I studied Eiffel in college and have a buddy who used to program in
that sad pathetic language, so I do know what I am talking about.
- - - - - - - - - - - - - - - - - -
J M Burton
FreeBSD Consulting & Security Administration
* * * This is a .sig virus. Copy it into your .sig to propagate. * * *



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

Date: Thu, 08 Nov 2001 03:17:27 GMT
From: "Rob - Rock13.com" <rob_13@excite.com>
Subject: Re: Can perl open a new browser window without embedding Javascript?
Message-Id: <Xns9152E28F468E2rock13com@64.8.1.226>

Jürgen Exner <news:3be82c18@news.microsoft.com>:

> "Qunfeng Dong":
>> Is there a way in perl itself to open a new browser window
>> similar to javascript's window.open()? Thanks! 
> 
> Sure. On a Windows OS just do a
>     system ("explorer.exe");
> and a new IE window will open (if explorer.exe is in your
> path). Same on a Unix or Mac, just call the proper command to
> launch the browser. 

explorer.exe is the windows file manager. iexplore.exe is Internet 
Explorer.

-- 
Rob - http://rock13.com/
Web Stuff: http://rock13.com/webhelp/


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

Date: Wed, 07 Nov 2001 22:53:24 -0500
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: DB module to store references?
Message-Id: <3BEA01B4.5F76C6D@earthlink.net>

Phil R Lawrence wrote:
> 
> "Andrew Cady" <please@no.spam> wrote:
> 
> > "Phil R Lawrence" <prlawrence@lehigh.edu> writes:
> > > FWIW, the data I need to sort by is not in the file, so I can't
> > > use a plain UNIX utility such as sort.  I am noting a unique
> > > identifier found on each report in the file and doing a database
> > > lookup to sort those unique identifiers by related information
> > > found in the database.
> 
> Here's a clarification...
> 
> Orig File:
> -----------
> SSN 000-00-0000
>   blah blah...
>   foo foo...
> SSN 444-44-4444
>   blah blah...
>   foo foo...
> SSN 222-22-2222
>   blah blah...
>   foo foo...
> -----------
> 
> # all of the following is for concept only...
> my (%reports,$key,$lines);
> while (<>) {
>     if (/^SSN/) {
>         $reports{$key}{lines} = $lines if defined $key;
>         $lines .= $_;
>         chomp( $key = $_);
>         $key =~ s/^SSN//;
>     } else {
>         $lines .= $_;
>     }
> }
> 
> for (keys %reports) {
>     $sth_get_sort_address->execute( $_ );
>     $reports{$_}{sort_address} = $sth_get_sort_address->fetch;
> }
> 
> # from memory
> my @sorted_keys =
>     sort { $reports{$a}{sort_address} <=>$reports{$a}{sort_address} }
>     keys $reports;
> 
> print OUT $reports{$_}{lines} for @sorted_keys;

This makes your problem a bit clearer.

Here's my suggestion:

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

$DB_BTREE->{'flags'} = R_DUP ;
tie %hash, 'DB_File', undef, undef, undef, $DB_BTREE;

$/ = "SSN "; <>;
while( <> ) {
    chomp; # remove "SSN " from end of $_.
    $sth_get_sort_address->execute( /(.*)/ );
    my ($sortkey) = $sth_get_sort_address->fetchrow_array;
    $sth_get_sort_address->finish;
    $hash{ $sortkey } = "SSN " . $value;
}

my $x = tied %hash;
my ($key, $value, $status) = ('', '', 0);
for($status = $x->seq($key, $value, R_FIRST) ;
    $status == 0 ;
    $status = $x->seq($key, $value, R_NEXT) ) {
    print $value;
}
__END__

-- 
Klein bottle for rent - inquire within.


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

Date: 7 Nov 2001 19:45:53 -0800
From: bill@wirespring.com (Bill Gerba)
Subject: DBD::Mysql arbitrarily creating duplicate entries
Message-Id: <516329be.0111071945.4679d40e@posting.google.com>

Hello all,

I've encountered a strange problem that I can't pin down to Perl or
Mysql, so please tell me what you think:

I have a CGI that takes a set of 'template' mysql database files (so
the actual .frm, .MYD and .MYI files) and copies them to a new
directory in my /mysql/data directory, thus creating a new database. 
I then connect to it with DBD::Mysql and attempt to insert data into
the tables in there.  Oddly, though, it seems to run each query twice,
duplicating every row that I insert.  And it looks to be that perl is
actually executing the statement twice, since I basically did the
following:

foreach my $x (1..10) {
    $query->prepare("blah blah $x");
    if ($query->execute() { $query->finish(); }
    else { print "problem: $!"; }
}

If I make 10 queries, I get 20 entries in my table, and 10 lines
saying "problem: duplicate value found for key... " or something like
that.  So Perl seems to be the culprit.  I don't have any loops or
anything that could be suspect like that, which leaves me very
confused.  Does anybody have any ideas about what this could possibly
be?  I don't think that there's any more information that could be
particularly useful.  This code duplicates values consistantly in this
particular script, and I've had this problem periodically elsewhere,
but not with this severity.  I'm running Perl 5.6.1 on Linux 2.4.10
with MySQL 3.23 and the newest DBI and DBD::Mysql modules.

Thanks,

Bill


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

Date: Thu, 08 Nov 2001 04:09:12 GMT
From: garry@ifr.zvolve.net (Garry Williams)
Subject: Re: DBD::Mysql arbitrarily creating duplicate entries
Message-Id: <slrn9uk1b8.qv.garry@zfw.zvolve.net>

On 7 Nov 2001 19:45:53 -0800, Bill Gerba <bill@wirespring.com> wrote:
> I've encountered a strange problem that I can't pin down to Perl or
> Mysql, so please tell me what you think:
> 
> I have a CGI that takes a set of 'template' mysql database files (so
> the actual .frm, .MYD and .MYI files) and copies them to a new
> directory in my /mysql/data directory, thus creating a new database. 
> I then connect to it with DBD::Mysql and attempt to insert data into
> the tables in there.  Oddly, though, it seems to run each query twice,
> duplicating every row that I insert.  And it looks to be that perl is
> actually executing the statement twice, since I basically did the
> following:
> 
> foreach my $x (1..10) {
>     $query->prepare("blah blah $x");
>     if ($query->execute() { $query->finish(); }
>     else { print "problem: $!"; }
> }
> 
> If I make 10 queries, I get 20 entries in my table, and 10 lines
> saying "problem: duplicate value found for key... " 

I don't believe you.  The value of $! will never contain such a
string.  Plus prepare() is a database handle method and execute() is a
statement handle method.  I don't believe that this code executes
without other errors.  

> or something like
> that.  

Maybe you'd like to show us the real code.  

Maybe you'd like to split it first to eliminate the "copying" as a
part of the problem.  

It would also be wise to dump the table with the mysql program
*before* running the problem code.  

> So Perl seems to be the culprit.  

Not that you've shown here.  You're not showing us any Perl code that
could produce such results.  

> I don't have any loops or
> anything that could be suspect like that, which leaves me very
> confused.  Does anybody have any ideas about what this could possibly
> be?  I don't think that there's any more information that could be
> particularly useful.  

But there is.  

> This code duplicates values consistantly in this
> particular script, and I've had this problem periodically elsewhere,
> but not with this severity.  

Show the code for this problem (in another post).  

Find a minimal program that illustrates your problem.  Show the data
and the results and what you expected.  

-- 
Garry Williams


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

Date: Wed, 07 Nov 2001 19:52:28 -0800
From: Jeff Zucker <jeff@vpservices.com>
Subject: Re: Help: simple perl question on Windows
Message-Id: <3BEA017C.7E712A85@vpservices.com>

Garry Williams wrote:
> 
> The shell in question *cannot* accomplish what the OP wants to
> accomplish.  Finding out how to use it won't change that.

All he has to do is put "perl " in front of his script name when he runs
it and he can accomplish it fine.  Is it lame that the shell requires
that?  Sure.  But does that mean he can't use the shell in question to
accomplish what he wants?  No.

-- 
Jeff



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

Date: 8 Nov 2001 04:03:27 GMT
From: Murvin Ming-Wai Lai <mmlai@sfu.ca>
Subject: How to find length of scalar var?
Message-Id: <9sd06f$is5$1@morgoth.sfu.ca>


Hi all,

  I have a question on scalar variable..  Which is, how to find its
length?  If it is a scalar array, then I know I can use $#array for
@array.  How about this:

  $abc = "123FFF";

how to find the length of that string?  Is there any build in function?
(by the way, what is the function "index" used for?).  I know that i can
use a while loop like this:
  while ($abc =~ /\d|\w/g) {
    $length++;
  }

to find the length.. but it will be too slow to have a while loop like
this. (imagine if I want to find the length of 10 thousand scalar
variables).


  Anyone has any idea?  I'm appreciated with any suggestion. =)

  Thanks

  Murvin

-- 
 .........................................................................
*>>>>Murvin Lai<<<<     >>>>--Muffin--<<<<     email: murvin_lai@sfu.ca *
*homepage:           http://www.sfu.ca/~mmlai              mmlai@sfu.ca *
`````````````````````````````````````````````````````````````````````````



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

Date: Thu, 08 Nov 2001 04:14:02 GMT
From: mjd@plover.com (Mark Jason Dominus)
Subject: Re: How to find length of scalar var?
Message-Id: <3bea0689.d89$46@news.op.net>

[mailed and posted]

In article <9sd06f$is5$1@morgoth.sfu.ca>,
Murvin Ming-Wai Lai  <mmlai@sfu.ca> wrote:
>  I have a question on scalar variable..  Which is, how to find its
>length?

Use the 'length()' function.

        $n = length($abc);

>(by the way, what is the function "index" used for?).  

It is used for locating one string inside of another one when you need
to know the position of the first string inside the second.


-- 
@P=split//,".URRUU\c8R";@d=split//,"\nrekcah xinU / lreP rehtona tsuJ";sub p{
@p{"r$p","u$p"}=(P,P);pipe"r$p","u$p";++$p;($q*=2)+=$f=!fork;map{$P=$P[$f^ord
($p{$_})&6];$p{$_}=/ ^$P/ix?$P:close$_}keys%p}p;p;p;p;p;map{$p{$_}=~/^[P.]/&&
close$_}%p;wait until$?;map{/^r/&&<$_>}%p;$_=$d[$q];sleep rand(2)if/\S/;print


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

Date: Wed, 07 Nov 2001 22:15:25 -0600
From: Tony Curtis <tony_curtis32@yahoo.com>
Subject: Re: How to find length of scalar var?
Message-Id: <87wv11yk2q.fsf@limey.hpcc.uh.edu>

>> On 8 Nov 2001 04:03:27 GMT,
>> Murvin Ming-Wai Lai <mmlai@sfu.ca> said:

> Hi all,

>   I have a question on scalar variable..  Which is, how
> to find its length?

The LENGTH of a string.  How to find the LENGTH?  A tricky
problem, finding the LENGTH of a string.

How could you miss it?

hth
t
-- 
Oh!  I've said too much.  Smithers, use the amnesia ray.


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

Date: Thu, 08 Nov 2001 04:20:34 GMT
From: "G Harper" <vze34thh@verizon.net>
Subject: Re: How to find length of scalar var?
Message-Id: <mKnG7.1402$o16.99126@typhoon2.gnilink.net>


"Tony Curtis" <tony_curtis32@yahoo.com> wrote in message
news:87wv11yk2q.fsf@limey.hpcc.uh.edu...
> >> On 8 Nov 2001 04:03:27 GMT,
> >> Murvin Ming-Wai Lai <mmlai@sfu.ca> said:
>
> > Hi all,
>
> >   I have a question on scalar variable..  Which is, how
> > to find its length?
>
> The LENGTH of a string.  How to find the LENGTH?  A tricky
> problem, finding the LENGTH of a string.
>
> How could you miss it?
>
> hth
> t
> --
> Oh!  I've said too much.  Smithers, use the amnesia ray.

I rather enjoy the original solution :-)


=-=-=-=-=-=-=-=-=-=-
I don't have a signature.




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

Date: 07 Nov 2001 23:21:37 -0500
From: Joe Schaefer <joe+usenet@sunstarsys.com>
Subject: Re: How to find length of scalar var?
Message-Id: <m3adxxopta.fsf@mumonkan.sunstarsys.com>

Murvin Ming-Wai Lai <mmlai@sfu.ca> writes:

>   I have a question on scalar variable..  Which is, how to find its
> length?  If it is a scalar array, then I know I can use $#array for
> @array.  

Better to just put @array in a scalar context:

  $num_elts = @array;

> How about this:
 
>   $abc = "123FFF";
> 
> how to find the length of that string?  

By applying the length() function to it.  In the perlfunc documentation,
the core functions are broken into categories- I find that breakdown to
be very useful.  Look for it in "Perl Functions by Category" with

  % perldoc perlfunc

Then you can pull out the particular function of interest with something
like

  % perldoc -f length

HTH
-- 
Joe Schaefer   "What a waste it is to lose one's mind. Or not to have a mind is
                           being very wasteful. How true that is."
                                               -- Dan Quayle



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

Date: Thu, 08 Nov 2001 02:25:54 GMT
From: garry@ifr.zvolve.net (Garry Williams)
Subject: Re: IO::SOCKET:INET
Message-Id: <slrn9ujr9i.qv.garry@zfw.zvolve.net>

On Wed, 07 Nov 2001 12:20:46 -0500, John Edl <johnedl@us.ibm.com>
wrote:

> I am trying to test if the dhcp daemon is running on a Unix server.
> It listens on port 67 using UDP only.  I am using the following to
> test:
> 
> use IO::Socket;
>         $sock=IO::Socket::INET->new(
>         PeerAddr=>$host,
>         PeerPort=>67,
>         Proto=>'udp',
>         Timeout=>$timeout || 3
>   );
> 
> hostname is being passed to the subroutine.  This always returns a value
> in $sock even though the
> dhcp daemon is not running on the host.


What should it do?  The UDP protocol is connectionless.  You now have
a socket that can be used to send datagrams to the presumed server.
The socket is perfectly valid, since it doesn't maintain a connection.
You can use it to send messages all day.  If the server isn't running
the packets will be dropped by the destination host and an ICMP packet
will probably be returned.  Since you are not listening to ICMP, that
will not matter.  [1]


> Any ideas?


Send a datagram that conforms to the protocol your server expects and
that requires the server to send a response.  Wait for the response
until you are tired of waiting any more[2].  Depending on the
reliability of the physical layer between you and your server, you may
want to re-send the message in an effort to recover from a dropped
packet along the way.  Wait for the response again.  Lather, rinse,
repeat.  Once you are convinced that the server is not responding,
declare it so.  You probably want to use the send() and recv() methods
for this.  

Pain in the butt, eh?  

See the perlipc manual page.  

[1] Using the ICMP protocol is a privileged operation and would
require authorization on most machines.  Unix would require the
process to be running with an effective user ID of root.  Examples of
commands that use this protocol are ping(1) and traceroute(1).  The
latter uses it in a creative way that may even be applicable to your
problem, although not directly using the command.  The manual page
describes the technique on most systems.  

[2] This means reading the socket, but arranging for it to time out
after whatever time you deem is appropriate.  The constructor for
IO::Socket::INET does not do this for you when you set its Timeout
attribute.  See the perlipc manual page and the perlfaq8 manual page.  

-- 
Garry Williams


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

Date: Wed, 07 Nov 2001 21:47:13 -0500
From: Benjamin Goldberg <goldbb2@earthlink.net>
Subject: Re: Is it possible to convert a UNIX shell command into PERL?
Message-Id: <3BE9F231.7D4961A6@earthlink.net>

Dan Nguyen wrote:
> 
> I would like to convert one of the two lines below from UNIX shell
> into perl but I was not able to do it.
> Please HELP HELP HELP!

You'd likely have better luck if you understood what each part of the
shell script was doing.  If you already do know, sorry... I'm just
assuming that because you're presenting the shell scripts instead of
saying what you want your program to do.

> find . -name "*.h" -follow -print | sed -e 's/^/\"/;s/$/\"/' |
> xargs wc -l | sed '$\!d' | nawk '{print $1}'

What this does:
1) find all files, starting in . whose name ends in .h, following
symbolic links, and print the results.
2) Put at the beginning and end of each line with '"'.
3) Batch up the filenames in groups such that each group will fit onto a
commandline along with 'wc -l' [there's a system limit on how much stuff
can go on one commandline], then run wc -l with each group.
4) Remove all lines except the last [this discards the output of all
runs of wc -l except the last one.  This is a bug in the above script]
5) Print the first field.

> OR
> 
>  wc -l "`find \. -name '*.h' -follow -print`" | sed '$\!d' |
> nawk '{print $1}'

What this does:
1) same as 1) above.
2) Run wc -l with *all* those filenames [if there are more filenames
than can fit on a commandline, this script croaks here]
3, 4) same as 4, 5) above.

In other words, what you want is a script which does a linecount on all
of your .h files, and prints out the sum.

#!/usr/local/bin/perl -w
use strict;
use File::Find qw(find);
my $linecount = 0;
sub wanted {
    return unless /\.h\z/ && -f;
    open( local(*THEFILE), "<", $_ ) or warn("$_ : $!\n"), next;
    $linecount += tr/\n// while sysread(THEFILE, $_, 8192);
}
find({ follow => 1, wanted => \&wanted}, '.');
print $linecount, "\n";
__END__

Patrick Spinler posted code which is almost correct, but which has a
couple of deficiencies... first, he thought the ignored your -follow
argument to find, and second, uses the external program wc, which is
slower than doing the line counting from within perl.

-- 
Klein bottle for rent - inquire within.


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

Date: Thu, 08 Nov 2001 04:08:06 +0200
From: "Zak McGregor" <zak@mighty.co.za>
Subject: Re: map question
Message-Id: <20011108.040806.1782436840.6054@mighty.co.za>

In article <m34ro6av2v.fsf@DCCMBX01.njitdm.campus.njit.edu>, "Mona Wuerz"
<wuerz@yahoo.com> wrote:

>> Why would oncatenating an empty string to the reverse($_) command
>> change anything?
> 
> It changes context. Appending "" has the same effect as:
> 
> @array=map { scalar reverse($_) } reverse split(/\./,
> reverse($filename), 2) ;
> 
> In list context, reverse returns the arguments in reverse order:
> 
> ~ $ perl -wle '$,=$"; print reverse qw/one two three/' three two one
> 
> In scalar context, it returns the reversed scalars that you expected.
> 

Ah, thanks! I knew I'd missed something.

Cheers

Zak


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

Date: Thu, 08 Nov 2001 02:07:51 GMT
From: Bart Lateur <bart.lateur@skynet.be>
Subject: Re: map question
Message-Id: <6vpjutok54phg5ok0jnk7o8e6jm0ciobua@4ax.com>

Zak McGregor wrote:

>Why would oncatenating an empty string to the reverse($_) command change
>anything?

Context. reverse() in scalar context turns the scalar parameter
backwards; reverse() in list context just swaps the parameters. or the
latter, if you have only one parameter, it'll appear to do nothing.

	$, = "#"; $\ = "\n";
	print reverse "abc", "123"; 	# list context
	print reverse "abc"; 	# list context, 1 parameter
	print scalar reverse "abc";	# scalar context, 1 parameter
	print scalar reverse "abc", "123";# scalar context, 2 parameters
-->
	123#abc
	abc
	cba
	321cba

	
-- 
	Bart.


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

Date: Thu, 08 Nov 2001 03:00:52 GMT
From: Martien Verbruggen <mgjv@tradingpost.com.au>
Subject: Re: Opening/creating files
Message-Id: <slrn9ujtbg.1on.mgjv@verbruggen.comdyn.com.au>

On Thu, 08 Nov 2001 02:01:22 GMT,
	G Harper <vze34thh@verizon.net> wrote:
> "Tad McClellan" <tadmc@augustmail.com> wrote in message
>>
>> What would be the point of creating an empty file to read from?
>>
> 
> "Martien Verbruggen" <mgjv@tradingpost.com.au> wrote in message

>> If, however, there is another process that creates the file, then
>> there is a race condition. The OP never mentioned this. If the OP
>> states a bit more clearly what is to be achieved, maybe we can give
>> better advice :)

> I'm making a page hit log based on visitor's IP.  If nobody has viewed the
> page yet, the IP log .txt file must be created.  The first access to the
> file in my program reads its contents.

You are aware that the IP address that you get from a web server
cannot uniquely be linked to a user, right? If you're really
interested in IP addresses, that's fine, but if you're trying to get
'unique user' information this way, then it won't work (think of proxy
servers, for example).

While it is possible to do what you're doing yourself, and it isn't
that hard (use groups.google.com to find some solutions posted here in
the past), it is also such a commonly requested task that there is a
module available from CPAN, called File::CounterFile, which seems to
do exactly what you want. Without downloading or testing it, I'd guess
you'd use it something like:

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

my $address = $ENV{REMOTE_ADDR} || "no_ip"; # paranoia

$File::CounterFile::DEFAULT_DIR = "/path/to/counter_dir";
my $counter = File::CounterFile->new($address);
my $value = $counter->inc();

print "Content-Type: text/plain\n\n$value\n";
__END__

This uses flock(), so it may not work on win95 and win98 (I don't know
what the status of the implementation of flock is on those platforms).

Martien

PS. Note that 'use strict;' should be in lower case. On a file system
that doesn't care about case, this may appear to work, but Perl itself
is case sensitive. Not using the correct case for modules may
introduce some hard to track down bugs (although it probably wouldn't
in this case)
-- 
                                | 
Martien Verbruggen              | True seekers can always find
Trading Post Australia Pty Ltd  | something to believe in.
                                | 


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

Date: Thu, 08 Nov 2001 04:00:08 GMT
From: "G Harper" <vze34thh@verizon.net>
Subject: Re: Opening/creating files
Message-Id: <crnG7.1395$vM6.82628@typhoon1.gnilink.net>


"Martien Verbruggen" <mgjv@tradingpost.com.au> wrote in message
> > I'm making a page hit log based on visitor's IP.  If nobody has viewed
the
> > page yet, the IP log .txt file must be created.  The first access to the
> > file in my program reads its contents.
>
> You are aware that the IP address that you get from a web server
> cannot uniquely be linked to a user, right? If you're really

Not using it to track specific users, but rather to identify (mostly) unique
hits.  Not too concerned for my level and purpose of implementation.

> interested in IP addresses, that's fine, but if you're trying to get
> 'unique user' information this way, then it won't work (think of proxy
> servers, for example).
>
> While it is possible to do what you're doing yourself, and it isn't
> that hard (use groups.google.com to find some solutions posted here in
> the past), it is also such a commonly requested task that there is a
> module available from CPAN, called File::CounterFile, which seems to
> do exactly what you want. Without downloading or testing it, I'd guess
> you'd use it something like:
>
> #!/usr/local/bin/perl -w
> use strict;
> use File::CounterFile;
>
> my $address = $ENV{REMOTE_ADDR} || "no_ip"; # paranoia
>
> $File::CounterFile::DEFAULT_DIR = "/path/to/counter_dir";
> my $counter = File::CounterFile->new($address);
> my $value = $counter->inc();
>
> print "Content-Type: text/plain\n\n$value\n";
> __END__
>
> This uses flock(), so it may not work on win95 and win98 (I don't know
> what the status of the implementation of flock is on those platforms).
>

I'm still very new to Perl, and I'm doing what I can to use _no modules for
now...
I know it's a sin but it makes me think a lot harder and understand a lot
more while I'm learning.
I'll learn to change the oil before buy the turbo intake (so to speak).
I'll check the docs though, for future reference.

> Martien
>
> PS. Note that 'use strict;' should be in lower case. On a file system
> that doesn't care about case, this may appear to work, but Perl itself
> is case sensitive. Not using the correct case for modules may
> introduce some hard to track down bugs (although it probably wouldn't
> in this case)

Whoops :-)

> --
>                                 |
> Martien Verbruggen              | True seekers can always find
> Trading Post Australia Pty Ltd  | something to believe in.
>                                 |

Thanks for all the feedback.. and sorry about the double post, dare I say...
I use Verizon :\




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

Date: Thu, 08 Nov 2001 04:42:13 GMT
From: Martien Verbruggen <mgjv@tradingpost.com.au>
Subject: Re: Opening/creating files
Message-Id: <slrn9uk39k.1on.mgjv@verbruggen.comdyn.com.au>

On Thu, 08 Nov 2001 04:00:08 GMT,
	G Harper <vze34thh@verizon.net> wrote:
> 
> "Martien Verbruggen" <mgjv@tradingpost.com.au> wrote in message
>> > I'm making a page hit log based on visitor's IP.  If nobody has viewed the
>> > page yet, the IP log .txt file must be created.  The first access to the
>> > file in my program reads its contents.

[snip suggestion to use File::CounterFile]

> I'm still very new to Perl, and I'm doing what I can to use _no modules for
> now...
> I know it's a sin but it makes me think a lot harder and understand a lot
> more while I'm learning.

It's not a sin. It's just wasteful, unless you're doing things to
learn :)

You might also want to have a look at Randal Schwartz's WebTechniques
column, at http://www.stonehenge.com/merlyn/WebTechniques/

> I'll learn to change the oil before buy the turbo intake (so to speak).
> I'll check the docs though, for future reference.

Ok. Reading back over your program that you posted earlier, I have a
few suggestions:

Make a decision on whether you want to keep separate log files for
each IP address, or whether you want to keep a single file.

If you decide to go with separate files, then you should implement
something like what you were going to do: Create a file if it doesn't
exist, otherwise open and update it. In both cases, you would not open
the file for read only, but you'd open it for update. This would
neatly create the file for you if it didn't exist yet (more on this
later).

If you decide to go with a single file, use one of the tied interfaces
to DB files on disk. This will greatly improve the speed with which
this works, and make your life a lot easier (more later again).

To use separate files you could do something like:

#!/usr/local/bin/perl -w
use strict;
use Fcntl qw(:flock :seek);

my $BASEDIR = "/tmp"; # change to whatever you need

# Simplistic version of File::CounterFile
sub update_counter
{
	my $addr = shift || "no_ip"; # paranoia
	my $file = "$BASEDIR/$addr.log";
	open(my $cf, "+>> $file") or die "Couldn't open $file: $!";
	flock $cf, LOCK_EX;
	seek $cf, 0, SEEK_SET;
	my $count = <$cf> || 0; 
	truncate $cf, 0;
	$count++;
	print $cf $count;
	return $count;
}

my $count = update_counter($ENV{REMOTE_ADDR});
print "Content-Type: text/plain\n\n$count\n";
__END__

Note that flock is used on the file handle, not on the file name.
If you are on a Perl before 5.6.0, you can't use a lexical file handle
like I do, and you may need to use a local(*CF), and replace all
references to $cf with CF. In both cases, the file will be closed when
the subroutine returns (and the lock will be released.

If you want to do it all in one file, maybe something like:

#!/usr/local/bin/perl -w
use strict;
use Fcntl qw(:flock :DEFAULT);

my $LOGFILE = "/tmp/address.log";
my $LOCKFILE = "/tmp/address.log.lock";

my $address = $ENV{REMOTE_ADDR} || "no_ip";

# Get a lock
open(my $lf, ">$LOCKFILE") 
	or die "Couldn't open lock file '$LOCKFILE': $!";
flock $lf, LOCK_EX;

use SDBM_File;
tie my %log, "SDBM_File", $LOGFILE, O_RDWR | O_CREAT, 0666
	or die "Couldn't tie SDBM '$LOGFILE': $!";

my $count = ++$log{$address};

print "Content-Type: text/plain\n\n$count\n";
__END__

You can use any other dbm implementation, or any other hash-based tie,
but SDBM is guaranteed to be available under all Perls, IIRC.

Some notes:

I use a separate lock file in this example, since the files the dbm
generates can have weird and unpredictable names (not entirely true,
but using a separate lock file is always safer and better, especially
if you need to be able to switch to another dbm implementation).

I didn't close any files or tied dbms explicitly, but left it up to
the OS to do this. If you'd rather be explicit, untie() and close()
right after the line that assigns to $count.

Don't explicitly unlock any of the files if you are going to close
them anyway. You should only do that when you plan on keeping the file
open after unlocking it. When you are going to close the file, it will
be unlocked automatically for you (and on older Perls this also makes
sure that any flushing is done correctly).

Martien
-- 
                                | 
Martien Verbruggen              | Little girls, like butterflies, need
Trading Post Australia Pty Ltd  | no excuse - Lazarus Long
                                | 


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

Date: Thu, 08 Nov 2001 02:57:00 GMT
From: "Turtle" <turtle*no-spam*@iislands.com>
Subject: Re: Oracle DBI Question
Message-Id: <0wmG7.429943$ME2.49227347@typhoon.kc.rr.com>

Thanks

Turtle

"Douglas Wilson" <dwilson@gtemail.net> wrote in message
news:3be9d95f.979222@news...
> On Wed, 07 Nov 2001 23:53:06 GMT, "Turtle" <turtle*no-spam*@iislands.com>
wrote:
>
> >The configuration for the project required a central server with the
> >database on it accessed from many remote clients. MySQL handles this with
> >ease so I thought it would be a no brainier for Oracle.
> >
> >
> >The question is what else do I need to load to get Oracle to do this.
Anyone
> >worked through this type of situation before? I am using the latest
version
> >of 8i and Perl.
>
> If you want to use DBD::Oracle, you'll need some Oracle client software on
the
> local machine. If you use DBD::Proxy you won't, but DBD::Oracle would be
> preferable I think.
>
> Although setting up the  Oracle client software is OT for perl, I think
its
> been discussed on the DBI mailing list. Search the archives
> at http://dbi.symbolstone.org
>




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

Date: Thu, 08 Nov 2001 10:03:27 +0800
From: hugo <hugo@fractalgraphics.com.au>
Subject: passing array values from perl to javascript 
Message-Id: <3BE9E7EF.DC65BD88@fractalgraphics.com.au>

Hi 

I am trying to pass an array with values from a perl to a javascript
array, then open a new window which displays the javascript array
values. I am reading in the perl array into the javascript array with
print statements, and this seems to work well (when I look at thepage
source). However, when I try to transfer the javascript array values to
a new window, and display them, nothing happens. An alert statement
attempting to display the [0] index value of the javascript array states
that it is undefined. 

Here is my code:

1. First, in my perl code, I read fill in the javascript array with
values from the perl array (@data is my perl array and jsinfile is my
javascript array): 

print "<SCRIPT LANGUAGE=\"javascript\">";	
print "var jsinfile = new Array();";
for ($i = 0; $i < @data; $i++) {
chomp $data[$i];
print "jsinfile[$i] = \"$data[$i]\"";  
}
print "</SCRIPT>"; 

Then I have a form with a button to view the new page, with an onClick
statement, passing the jsinfile array to the function which opens the
new page: 

print "<FORM METHOD=\"POST\" ENCTYPE=\"multipart/form-data\">";
print "<p>View double-spaced file?";
print "<INPUT TYPE=\"SUBMIT\" VALUE=\"View\"
onClick=\"javascript:open_outfile1(jsinfile)\">";
print "</FORM>";    

Then I have the javascript function which is activated by onClick and
opens the new window. The new window is opened but no jsinfile values
are displayed in the page. Note that this function occurs earlier in the
code (i.e. higher up), but that shouldn't matter. The window alert on
the third line states that jsinfile is undefined. 

print "<SCRIPT LANGUAGE=\"javascript\">";
print "function open_outfile1(jsinfile) {"; 
print "window.alert(\"jsinfile (in javascript function) is : \" +
jsinfile[0]);"; 
print "newWindow =
window.open('','newWin','toolbar=yes,location=yes,scrollbars=yes,resizable=yes,width=500,height=500,');";
print "newWindow.document.write(\"<html><head><title>Double spaced
file<\/title><\/head><body bgcolor=#FFFFFF>\");";
print "for (i =0; i < jsinfile.length; i++) {";
print "		newWindow.document.writeln(jsinfile[i]);";
print "    newWindow.document.writeln(\"<br>\");";
print "}";
print "newWindow.document.write(\"<\/body></\html>\");";
print "newWindow.document.close();";  
print "}";	
print "</SCRIPT>"; 

I think I may be doing something wrong in passing the value of jsinfile
to the javascript function. Perhaps filling in values for jsinfile by
printing it in the first window, does not make it follow that they can
be transferred to another window? I am not very clear on that. If this
is not the way to do it, how then do I open a new window and transfer
array values from a perl array to the new window? Note that I do not
want to do this with a FORM ACTION statement, as then my main window
will be changed (not a new window opened).  

Any help will be greately appreciated.  

Thanks

Hugo 

-- 
Dr Hugo Bouckaert
R&D Support Engineer, Fractal Graphics 
57 Havelock Street, West Perth 6005
Western Australia 6009
Tel: +618 9211 6000 Fax: +618 9226 1299
Email:hugo@fractalgraphics.com.au
Web: http://www.fractalgraphics.com.au


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

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


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