[8706] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 2323 Volume: 8

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Apr 14 23:07:44 1998

Date: Tue, 14 Apr 98 20:00:24 -0700
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Tue, 14 Apr 1998     Volume: 8 Number: 2323

Today's topics:
    Re: Child .bat inheriting Perl %ENV (Martin Oakley)
        considerations for global variables? <dtbaker_@flash.net>
        correct useage of the if statement (Steve)
    Re: correct useage of the if statement (Jason)
    Re: File download problem in IE4.0 <rothd@xrxoxtxhx.xnxextX>
    Re: File Renaming <jdf@pobox.com>
        Four asses!? <sfarrell+usenet@farrell.org>
        have DBM assoc array functions been enabled in a win32  <dtbaker_@flash.net>
    Re: HELP!!! Script to perform website search <gwynne@utkux.utk.edu>
    Re: Hide or Encrypt perl source code <kaehny@execpc.com>
    Re: How to read systemcommand value to a variable? <grinch@whoville.com>
    Re: info on cookies <ljz@asfast.com>
    Re: Learning Perl <dtbaker_@flash.net>
    Re: multiple file/directory transfer with Net::FTP <jdf@pobox.com>
    Re: Need a Free Perl Data Base to the Web (Rael Dornfest)
    Re: Numeric validation (Jeffrey Drumm)
        Perl utility to surf through 'syslog' files........ <sjhill@plutonium.net>
    Re: perl's 'grep' vs. shell's 'grep' (Tad McClellan)
        Possible bug in dbm routine?!?! (DR TE$TH & THE ELECTRIC MAYHEM)
        understanding Perl<->.html forms? <dtbaker_@flash.net>
    Re: Win32:GetFreeDiskSpaceEx <rothd@xrxoxtxhx.xnxextX>
        Digest Administrivia (Last modified: 8 Mar 97) (Perl-Users-Digest Admin)

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

Date: Wed, 15 Apr 1998 01:17:38 GMT
From: martin.oakley@usa.net (Martin Oakley)
Subject: Re: Child .bat inheriting Perl %ENV
Message-Id: <353409f8.87075281@news.bne.aone.net.au>

It works for me on NT Server 4.0 and win95
You might want to check $ENV{"TEST_ENV"} in the perl script - maybe
you are out of environment space (does that happen in NT?)


Build Administrator <bldadmin@esd.sgi.com> wrote:

>Under NT, when I system("somefile.bat") it doesn't have the environment
>I've established with %ENV.
>
>Is there a way to do this?   Example below prints nothing for TEST_ENV.
>
>Thanks.
>
>JR
>
>
>
># test.pl script
>
>$ENV{"TEST_ENV"} = 101;
>system("test.bat");
>
>#-------------------
>
>
>REM test.bat script
>
>echo off
>echo TEST_ENV: %TEST_ENV%
>
>REM ------------------
>



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

Date: Tue, 14 Apr 1998 20:31:11 -0600
From: Dan Baker <dtbaker_@flash.net>
Subject: considerations for global variables?
Message-Id: <35341BEF.8ED@flash.net>

I would like to learn more about the considerations and options for how
to use "global" variables in perl scripts which are not in a single
program.... i.e. a .html page may execute one script to create or modify
some values which need to be used by a different script at a later time.

Possible approaches I was considering are:
- writing/reading a text file with variable names/values
- using environmental variables??? do they exist in win32?
- ??? any other approaches?

-- 
# If you would like to reply directly, remove the _ from my username
# Thanx, Dan

* Use of my email address regulated by *
*  US Code Title 47, Sec.227(a)(2)(B)  *


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

Date: Wed, 15 Apr 1998 01:33:27 GMT
From: syarbrou@ais.net (Steve)
Subject: correct useage of the if statement
Message-Id: <35340de1.40938342@news.ais.net>

I have an if statement as follows:

elsif ($entry[22] == 6)
  {
     .......
     .. . . . . . .
  }

the value $entry[22] can be set to anything that starts with a 6 and
it accepts it as a valid entry.  I've tried the single quote and the
double one and nothing seems to prevent if from saying it's valid.
The value entered for entry[22] is 6NA and it things it's valid.  How
should I correctly set this up?  Thanks.

Steve


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

Date: 15 Apr 1998 01:46:41 GMT
From: robobob@blech.mindwell.com (Jason)
Subject: Re: correct useage of the if statement
Message-Id: <slrn6j84c1.jle.robobob@blech.mindwell.com>

On Wed, 15 Apr 1998 01:33:27 GMT, Steve <syarbrou@ais.net> wrote:
>I have an if statement as follows:
>
>the value $entry[22] can be set to anything that starts with a 6 and
>it accepts it as a valid entry.  I've tried the single quote and the
>double one and nothing seems to prevent if from saying it's valid.
>The value entered for entry[22] is 6NA and it things it's valid.  How
>should I correctly set this up?  Thanks.
>

if(6 == '6NA') { print "true!\n"; }

will print true because you used ==, the NA is not included in the comparison
because it is not a number, if you want to compare strings, you need to use
eq instead of == (since == will compare the two objects as numbers).

-- 
    Jason Kohles -- System Administrator -- XMission Internet Access
       jason@xmission.com (at work) jason@mindwell.com (at play)

       "We're not surrounded, we're in a target-rich environment!"


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

Date: 15 Apr 1998 02:11:02 GMT
From: "Dave Roth" <rothd@xrxoxtxhx.xnxextX>
Subject: Re: File download problem in IE4.0
Message-Id: <01bd6814$2af38940$0101a8c0@main2>



bidyut@yahoo.com wrote in article
<6h0dfl$tg2$1@nnrp1.dejanews.com>...
> Hi guys,
> 
> One more point i have found out after doing a lot of work
on that. If I
> hardcode the filename is CGI script, then IE is able to
download and show the
> file in browser. But if i try to get the filename
dynamically(i.e passing
> through post method from a form and obtaining it by using
> $query->param('filename')), then IE fails in showing up
the file. So, this
> means there is some problem in the filename due to the
different way of
> processing.

Do you have the ActiveDesktop active? Are your Mime types
mapped to perl.exe?
dave
-- 
============================================================
====
Dave Roth                               ...glittering
prizes and
Roth Consulting                     endless compromises,
shatter
rxoxtxdxxrxoxtxhx.xnXeXt               the illusion of
integrity

 My email address is disguised to fool automailers. Remove
the
                      X's to send me email.
************************************************************
****
Use of  this message or  email address  for commercial 
purposes
(including "junk" mailings) is strictly prohibited and
protected
under  current  international  copyright laws  and United
States
Code, Title 47, Chapter 5, Subchapter II.



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

Date: 14 Apr 1998 21:26:46 -0500
From: Jonathan Feinberg <jdf@pobox.com>
Subject: Re: File Renaming
Message-Id: <sonf6crd.fsf@mailhost.panix.com>

Zsolt Fazekas <zsolt@idigital.net> writes:

I have several comments for you.

> #!/usr/bin/perl

Especially because you're having a problem with your script, you
should use the -w switch.

> open (DIR, "+<file.txt") || die $!;

"DIR" is perhaps a confusing name for a file handle, though it's
perfectly legal.  Just my opinion.  Also, you're opening the file for
read/write access, but never writing to it.  You can just open
'<file.txt'.

> while (defined ($_=<DIR>)) {

There is a synonym for this construct, and it's spelled

   while (<DIR>) {  # which I find much more legible

>     $oldname= (chomp $_);

Whoops!  You've just assigned the number of characters removed by
chomp to $oldname.  Also, the use of parens is confusing.

>     if ($_=~ /jpg/ || /gif/) {  #leave other files alone

Heh.  This works, but for completely different reasons than you
think.  Alternates in a regex are separated with a vertical bar, "|".
Furthermore, the magical variable $_ is bound to an otherwise unbound
match operator, so that

    $_ =~ /foo/;

is *exactly* the same as

    /foo/;

I think you mean to say

   if (/jpg|gif/) {

although you probably mean to see if those patterns appear at the
*end* of the file name, i.e., are file extensions.  Therefore you
should say

   if (/\.(?:jpg|gif)$/)

but I won't explain everything there.  I'll leave something for you to
read in the docs!

>         $_=~ s/\w*/$i/;        #chop up to . and discard

Hmm.  Again, you don't need that "$_ =~" part, and I don't think your
regex is quite accurate.  What if there are two dots in the filename?

>         $newname=$_;
>         rename ($oldname,$newname) || die $!"; 

Is that really what your code says?  It shouldn't even compile, as
you're missing a quotation mark.

> close (DIR) || die $!";

Same comment.  Are you sure you really posted the code you're running?

If you had simply put in a print statement before the rename, you'd
have found out immediately that you weren't doing what you thought you
were doing.  That is a fundamental debugging technique.

   print "About to rename('$oldname', '$newname')...\n";

If you haven't done so already, you should buy _Learning Perl_, and do
all of the exercises in the book, cover to cover.  I hope this helps.

-- 
Jonathan Feinberg   jdf@pobox.com   Sunny Brooklyn, NY


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

Date: Wed, 15 Apr 1998 01:11:08 GMT
From: stephen farrell <sfarrell+usenet@farrell.org>
Subject: Four asses!?
Message-Id: <8790p7hosz.fsf@phaedrus.uchicago.edu>


I was very surprised to see four asses as the output of the following
code:

	#!/usr/local/bin/perl5.004
	
	use strict;
	my $l_ref = [ 1, 2, 3, 4 ];
	
	my $tmp;
	foreach $tmp (@$l_ref) {
		$tmp = "ass";
	}
	
	warn join("\n", @$l_ref);
	
	## EOF


I was under the impression that ONLY the following construct (or some
variation) would bring about these results:

	for (0..$#$l_ref) {
		$l_ref->[$_] = "ass";
	}

So I'm very confused about the variable $tmp in that first example.
Somehow it's not really it's own variable, but rather a pointer into
$l_ref's list.  Well, to be more accurate, I think this leaves me very 
confused about variables in perl in general.  I assumed everything was 
call-by-value unless a reference is used explicitely.  So now I'm
wondering, if I do:

	sub listfunc {
		return (1, 2, 3);
	}	

	join ("\n", listfunc());

does the list (1, 2, 3) get copied, or does join just get a (magic,
internal) reference to it?


if I haven't formulated my confusion well enough, let me know, i'll
try harder.  (And I promise to avoid SouthPark references as well.)

thanks.

--sf


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

Date: Tue, 14 Apr 1998 20:35:55 -0600
From: Dan Baker <dtbaker_@flash.net>
Subject: have DBM assoc array functions been enabled in a win32 port yet?
Message-Id: <35341D0B.58B7@flash.net>

I am just learning about perl, and the book I read mentioned the DBM
functions for assoc arrays which sounded great, but then mentioned that
they had not been enabled in the win32 port.... could someone let me
know if this is still true, or if it has been ported in a current
release of Perl5?  If, so, what version, and where to get it!
-- 
# If you would like to reply directly, remove the _ from my username
# Thanx, Dan


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

Date: Tue, 14 Apr 1998 20:59:06 -0400
From: "Bob Gwynne" <gwynne@utkux.utk.edu>
Subject: Re: HELP!!! Script to perform website search
Message-Id: <6h10ri$4eu$1@gaia.ns.utk.edu>

Purchase a copy of Web Client Programming with Perl by Clinton Wong,
otherwise known as the Abigail book.

Bob Gwynne
University of Tennessee
kmyers@syneractive.com wrote in message <6h0899$lf0$1@nnrp1.dejanews.com>...
>Can anyone tell me where I can find a script which when given a keyword and
>domain (ex. usatoday.com) returns all links to pages which contain the
>keyword?
>
>Thanks.
>
>-----== Posted via Deja News, The Leader in Internet Discussion ==-----
>http://www.dejanews.com/   Now offering spam-free web-based newsreading




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

Date: Tue, 14 Apr 1998 20:14:19 -0500
From: Mark Kaehny <kaehny@execpc.com>
Subject: Re: Hide or Encrypt perl source code
Message-Id: <6h11qn$6hl@newsops.execpc.com>

Chris Adams wrote:
> 
> According to Tom Christiansen  <tchrist@mox.perl.com>:
> >I can't see any danger with 755.  It's 777 that has naughtiness.  Being
> >able to read something is no danger.  In fact, it enhances security by
> >avoiding the oxymoronic security-through-obscurity myth.
> 
> Well, there are some scripts that it would be nice to not have world
> readble.  For example: our modem login system logs access to a MySQL
> database.  I want users to be able to check their usage but not anyone
> else's usage.  The database requires a username and password to connect,
> but then I have to put them in the perl script that checks usage.  How

Here is where the trouble starts. Why in the world do you have to or
want to
put them in the source code of the script? Here are three options all of
which are
better than just compiling the script - if you do that I'll just used
'strings' or the 
equivalent to get the login/password if I want. Compiling provide
negative security 
against serious threats since it provides a false sense of security. If
the level of 
security is just that a person can't get a non-encrypted string out of a
binary, that is 
essentially zero. I am always amazed when people think this actually
helps.

1) Have the script read a file with the
   login and password, and you can put the file in a safe place. 

2) Have the script connect to some other secure machine and ask for the
login/password.
   Do this if you don't want the login accessible on the machine at all.

3) Encrypt the string in the source. This will give the level of
security that
compiling does. Use one of the filter modules, or just xor some strings
into yours,
and do that in your script - then you won't "expose" the information
directly. 
The user willhave to do a little more work then just using strings or
such.

These are some trivial and insecure means.
People get paid for the more powerful ones :-)

Mark Kaehny


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

Date: Tue, 14 Apr 1998 21:09:42 -0400
From: "Grinch" <grinch@whoville.com>
Subject: Re: How to read systemcommand value to a variable?
Message-Id: <6h10ij$blr@fridge.shore.net>

Randal Schwartz wrote in message <8c4szwqyo6.fsf@gadget.cscaper.com>...

>>>>>> "Grinch" == Grinch  <grinch@whoville.com> writes:
>
>Grinch> Use backticks, like this:
>
>Grinch> $a = `finger|grep 75727`;
>
>And that would be further optimized in my programs to:
>
> @found = grep /75727/, `finger`;
>
>No need to waste a Unix process to do a little text manipulation. That's
>where Perl excels!


You're right, of course. I was looking at the question as 'how do I run a
program and capture its output', since the example wasn't provided in
context.

-grinch

----
"Of course coffee doesn't make the world go around. It
just makes it go faster." - me

Sherm Pendley
grinch@whoville.com
http://www.whoville.com





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

Date: 14 Apr 1998 22:03:45 -0400
From: Lloyd Zusman <ljz@asfast.com>
Subject: Re: info on cookies
Message-Id: <ltu37vlu2m.fsf@asfast.com>

abigail@fnx.com (Abigail) writes:

> Gilles Chong (glchy@csah.com) wrote on MDCLXXXVII September MCMXCIII in
> <URL: news:35332C56.7433130D@csah.com>:
> ++ Hi,
> ++ im playing with cookies for the moment. Generating them with a
> ++ javascript is very simple. But im stuck when it comes to getting the
> ++ cookie and reading it in Perl. It seems that there is NOT an env
> ++ variable which corresponds to the cookie.
> 
> Then that's a problem you have to take up with your server, not with Perl.

 ... although this question is also relevant to Perl, since there's a
Perl module called "CGI" which provides a method to access cookies.
Furthermore, this method doesn't require you to directly access any
environment variables, so you don't need to be concerned about this
detail.  This CGI module comes in the standard distribution of Perl
these days, and if you're using a Unix version of Perl which is
properly installed, you can see the documentation for this module by
typing "man CGI".

In these "man pages", look in the section labeled "NETSCAPE COOKIES"
for a very complete explanation of how to set and retrieve cookies
using the `cookie()' method of this CGI package.

Here's a quick summary of how you could use this package in your Perl
program to retrieve a cookie:

    use CGI;

    $id = new CGI;

    %cookieLookup = $id->cookie(-name=>'cookieName');
    # ... where 'cookieName' names the cookie you want to retrieve.

    # Then, you would do the following to access the various items
    # from your cookie:

    $item1 = $cookieLookup{'item1'};
    $item2 = $cookieLookup{'item2'};
    # ... etc. ...
    
You can check the above-mentioned docs for more details.

-- 
 Lloyd Zusman
 ljz@asfast.com


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

Date: Tue, 14 Apr 1998 19:58:11 -0600
From: Dan Baker <dtbaker_@flash.net>
Subject: Re: Learning Perl
Message-Id: <35341433.6040@flash.net>

Sundeep Singatwaria wrote:
> 
> Hi All
> I'm trying to learn Perl but 'm not able to find any pointers where I
> can start. Can somebody give some good pointers for begineers. Is it a
> necessity for one to be good in Unix Scripts before learning Perl.
> 
> Help appreciated
> -Sundeep
-----------
I'm just learning too, and have just finished "Perl5 for Dummies". It
was fast and easy reading that covered the basics pretty well.

I have a lot more questions about using Perl with html forms in
particular though.... If anyone has a good beginner explanation on
getting data to/from web pages to Perl I'd really like to hear about it!

Dan

Dan


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

Date: 14 Apr 1998 21:00:51 -0500
From: Jonathan Feinberg <jdf@pobox.com>
Subject: Re: multiple file/directory transfer with Net::FTP
Message-Id: <u37v6dyk.fsf@mailhost.panix.com>

Mir S Islam <mislam@mindspring.net> writes:

> Greetings all, is it possible to transfer multiple files and entire
> directory structure from one machine to another ?

I enclose a script I hacked up to do just that.  It goes in the
opposite direction from what you want, but it should give you some
ideas about the use of Net::Ftp in a real application.  I make no
claims about the quality of this code; I wrote it for my own use.  I
call it "ftp_get_tree."

    #!/c/perl/bin/perl -w
    use strict;
    use Net::FTP;
    use File::Path;
    use Getopt::Long;
    use Cwd;

    $|++;

    sub prompt          ($);
    sub passwd          ($);
    sub recursively_get ($$);

    my @binary_extensions = qw( 
		sea sit zip gz tgz
		z gif jpg jpeg moov
		mpg mpeg ra wav
	       );

    my ($host, $rdir, $ldir, $user, $pass);
    GetOptions( 
	  'host=s' => \$host,
	  'rdir=s' => \$rdir,
	  'ldir=s' => \$ldir,
	  'user=s' => \$user,
	 );

    $host ||= prompt 'Host';
    $user ||= prompt 'Username';
    $rdir ||= prompt 'Remote directory';
    $ldir ||= prompt 'Local directory';
    $pass = passwd "Password for $user\@$host";

    print "Opening connection to $host.\n";
    my $ftp = Net::FTP->new($host)
      or die "Can't create ftp session: $!";

    print "Logging in as $user.\n";
    $ftp->login($user, $pass) or die "Can't login to $host as $user: $!";

    recursively_get $rdir, $ldir;

    $ftp->quit;

    exit 0;
    ##########################################

    sub prompt ($) {
      my $prompt = shift;
      print "$prompt: ";
      chop(my $response = <STDIN>);
      $response;
    }

    sub passwd ($) {
      my $prompt = shift;
      system "stty -echo";
      print "$prompt: ";
      chop(my $word = <STDIN>);
      print "\n";
      system "stty echo";
      $word;
    }

    sub recursively_get ($$) {
      my ($rd, $ld) = @_;

      print "Getting remote directory $rd.\n";

      -e $ld or mkpath ($ld) or die "Can't create $ldir: $!";
      -d $ld or die "$ld exists and is not a directory."; 
      chdir $ld or die "Can't chdir $ld: $!";

      $ftp->cwd($rd) or die "Can't CWD $rd: $!";
      my %dirs = ();
      my $list = $ftp->dir();
      foreach my $rf (@$list) {
	$rf =~ /^total/ && next;
	my $rfname = (split ' ', $rf)[-1];
	$rf =~ /^d/ and ($dirs{"$rd/$rfname"} = "$ld/$rfname"), next;

	$rfname =~ /\.([^.]+)$/;  # set $1 to file extension
	my $binary = () = grep {$_ eq $1} @binary_extensions;
	printf   ("Getting remote file $rfname (%s).\n", 
	     $binary ? 'binary' : 'ascii');
	if ($binary) {$ftp->binary() or die "Can't set binary mode: $!"}
	else         {$ftp->ascii() or die "Can't set ascii mode: $!"}
	$ftp->get($rfname) or die "Can't get $rfname: $!";
      }

      while (my($rdir, $ldir) = each %dirs) {
	recursively_get $rdir, $ldir;
      }
    }
    __END__
-- 
Jonathan Feinberg   jdf@pobox.com   Sunny Brooklyn, NY


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

Date: 15 Apr 1998 01:33:48 GMT
From: rael@mars.dnai.com (Rael Dornfest)
Subject: Re: Need a Free Perl Data Base to the Web
Message-Id: <slrn6j83jr.6c9.rael@mars.dnai.com>

Also take a gander at the MySQL (http://www.tcx.se) database.
You'll also find links to the all-powerful DBI module and Mysql
DBD driver.

In article <6gutf4$4nd@fridge.shore.net>, Grinch wrote:
>smile_ wrote in message <3531F265.4950AEDD@cindy.fe.up.pt>...
>
>>Need a Free Perl Data Base to the Web, if you can help me send me one.
>
>
>If you're working for an educational or non-profit organization, mSQL is
>free. You can find it at <URL: http://www.hughes.com.au >. Whatever database
>you choose, mSQL or otherwise, once you've got the database itself installed
>and working, check out the DBI module and the appropriate DBD module from
>CPAN. <URL: http://www.perl.com >
>
>Did you _really_ want someone to email you all of the above??? :-)
>
>HTH!
>
>-grinch
>
>----
>"Of course coffee doesn't make the world go around. It
>just makes it go faster." - me
>
>Sherm Pendley
>grinch@whoville.com
>http://www.whoville.com
>
>
>


-- 
___________________________________________________________________________
Rael Dornfest                     Little fly, thy summer's play
Webmaven                          My thoughtless hand has brushed away.
DNAI                              Am not I a fly like thee?
rael@dnai.com                     Or art not thou a man like me?
http://www.dnai.com               For I dance and drink and sing,
                                  Till some blind hand shall brush my wing.
                                                 --William Blake, "The Fly"


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

Date: Wed, 15 Apr 1998 01:56:14 GMT
From: drummj@mail.mmc.org (Jeffrey Drumm)
Subject: Re: Numeric validation
Message-Id: <35360782.1118121613@news.mmc.org>

On Mon, 13 Apr 1998 23:40:53 +0200, N i c l a s O l o f s s o n
<gurun@acc.umu.se> wrote:

>Hell, I'm pretty used to unix man pages but I really have to say that
>perl has the worst I've seen in years. Written by hackers, for hackers,
>more of the "hard to write, should be hard to read"-type..

I have no _formal_ education in computer science, but find them both easy
to navigate, reasonably complete (although they assume _some_ programming
background and familiarity with Unix facilities and concepts, but not a
lot) and well organized.

The only thing I can remember making me spin my wheels a bit was the lack
of mention of the need for the Fcntl and POSIX modules to take advantage of
the constants used in many of the examples.

They certainly beat the hell out of  the C library man pages I've seen to
date  . . .

-- 
                           Jeffrey R. Drumm, Systems Integration Specialist
                                  Maine Medical Center Information Services
                                     420 Cumberland Ave, Portland, ME 04101
                                                        drummj@mail.mmc.org
"Broken? Hell no! Uniquely implemented." -me


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

Date: Tue, 14 Apr 1998 21:32:43 -0500
From: "Steven J. Hill" <sjhill@plutonium.net>
Subject: Perl utility to surf through 'syslog' files........
Message-Id: <35341C4B.FB7FDACC@plutonium.net>

I just finished this utility and thought that I would share it with
other people. I work at an ISP and needed a quick way to monitor what
services and how often they were being utilized. This also allows a
person to perhaps graph usage of different services as well. Please give
me feedback if you find it useful or if there are some Perl shortcuts
that I missed. Enjoy.


Steve


*******************************

#!/usr/bin/perl

# logsurf v0.1
# written by Steven J. Hill
# (c) Copyright 1998 by Plutonium, Inc.
#
# v0.1 - 04/14/98 - Original release to report system log statistics
# and allow for interactive surfing through it.

# Hash table for months.
%months = ("Jan",1,
           "Feb",2,
           "Mar",3,
           "Apr",4,
           "May",5,
           "Jun",6,
           "Jul",7,
           "Aug",8,
           "Sep",9,
           "Oct",10,
           "Nov",11,
           "Dec",12);

# Define numeric sort subroutine.
sub by_number {
  if($a < $b) {
    return 1;
  }
  elsif($a == $b) {
    return 0;
  }
  elsif($a > $b) {
    return -1;
  }
}
   
# Set default filenames.
$ifname = "/var/log/syslog";
$ofname = "output.txt";

# Default is to not surf log interactively.
$interactive = 0;

# Parse the command line.
if(@ARGV > 0) {
  while(@ARGV > 0) {
    $ARGV = shift(@ARGV);

    if($ARGV eq "-i") {
      $interactive = 1;
    }
    elsif($ARGV eq "-if") {
      $ifname = shift(@ARGV);
    }
    elsif($ARGV eq "-of") {
      $ofname = shift(@ARGV);
    }
    else {
      print "\n\nUsage:  logsurf [-h] [-i] [-if filename] [-of
filename]\n\n";
      print "    -h     Displays this help message.\n";
      print "    -i     Interactive parsing through log file.\n";
      print "    -if    Specify input log file.\n"; 
      print "    -of    Specify output log file (interactive
only).\n\n\n";
      exit(0);
    }
  }
}

# Open up the files.
if(-f $ifname && -T $ifname && -r $ifname) {
  open(SYSLOG,$ifname) || die "ERROR: Unable to open log file.\n";
}
else {
  die "ERROR: Unable to open log file.\n";
}
open(OUTPUT,">$ofname") || die "ERROR: Unable to open output file.\n";

# These variables are used for displaying status information. They
# can be removed for throughput savings. I like to see what is
# happening. All units are in bytes.
$filesize = 512 * (stat($ifname))[12];
$increment = $filesize / 10;
$increment_status = $increment;
$total_read = 0;

# Go through and collect totals for all types of log entries.
while(<SYSLOG>) {

  # Print status information in 10% increments.
  $total_read += length();
  if($total_read > $increment_status) {
    $percent = ($increment_status / $filesize) * 100;
    $increment_status = $increment_status + $increment;
    print $percent . "% Complete...\n";
  }

  # Parse the line into the different fields.
  split(/ {1,}/);

  # Get the beginning time and date for the first log entry.
  if($total_read == length()) {
    $log_start_month = $_[0];
    $log_start_day = $_[1];
    $log_start_time = $_[2];
    $log_start_hour = (split(/:/,$_[2]))[0];
  }

  # Parse the line and collect statistics.
  $_[4] =~ s/\[\w*\]://;
  $statistics{$_[4]}++;

}

# Get ending time and date for the last log entry.
$log_end_month = $_[0];
$log_end_day = $_[1];
$log_end_time = $_[2];
$log_end_hour = (split(/:/,$_[2]))[0];

# Close the log file.
close(SYSLOG);

# Print out statistics from the log file.
print "\n\nLOG FILENAME:  $ifname\n";
print "LOG START:  $log_start_month $log_start_day $log_start_time\n";
print "LOG END:    $log_end_month $log_end_day $log_end_time\n\n";
print "NO.       LOG TYPE       OCCURRENCES\n";
print "---    --------------    -----------\n";

# Sort the entries alphabetically. Tried sorting by occurences, but any
# logs with the same number of occurences will be lost when reversing
# the hash (see the perlfunc manpage about this).
$count = 1;
foreach $log (sort(keys %statistics)) {
  printf("%3d    %14s    %11.0f\n",$count,$log,$statistics{$log});
  $numbered_logs{$count} = $log;
  $count++;
}
$count--;
print "\n";

# Interactive log surfing stuff starts here. Exit program if it was
# not enabled.
if($interactive == 0) {
  close(OUTPUT);
  unlink($ofname);
  exit(0);
}

# Get log type selection.
$valid = 0;
while($valid == 0) {
  print "Select log type to view (1-$count): "; 
  $logsel = <STDIN>;
  chomp($logsel);
  if($logsel <= $count && $logsel > 0) {
    $logtype = $numbered_logs{$logsel};
    $valid = 1;
  }
}

# Get parsing start date from user.
$valid = 0;
while($valid == 0) {
  print "Enter parsing start date (MM-DD): "; 
  $work = <STDIN>;
  chomp($work);
  split(/-/,$work);
  $user_start_month = $_[0];
  $user_start_month =~ s/^0//;
  $user_start_day = $_[1];
  $user_start_day =~ s/^0//;
  if($user_start_month >= $months{$log_start_month} &&
    $user_start_month <= $months{$log_end_month} &&
    $user_start_day >= $log_start_day && $user_start_day <=
$log_end_day) {
    $valid = 1;
  }
}

# Get parsing end date from user.
$valid = 0;
while($valid == 0) {
  print "Enter parsing end date (MM-DD): "; 
  $work = <STDIN>;
  chomp($work);
  split(/-/,$work);
  $user_end_month = $_[0];
  $user_end_month =~ s/^0//;
  $user_end_day = $_[1];
  $user_end_day =~ s/^0//;
  if($user_end_month >= $months{$log_start_month} &&
    $user_end_month <= $months{$log_end_month} &&
    $user_end_day >= $log_start_day && $user_end_day <= $log_end_day) {
    $valid = 1;
  }
}

# Get parsing start hour from user.
$valid = 0;
while($valid == 0) {
  print "Enter hour to start parsing (HH): "; 
  $user_start_hour = <STDIN>;
  chomp($user_start_hour);
  if($user_start_hour >= $log_start_hour && $user_start_hour <=
$log_end_hour) {
    $valid = 1;
  }
}

# Get parsing end hour from user.
$valid = 0;
while($valid == 0) {
  print "Enter hour to end parsing (HH): "; 
  $user_end_hour = <STDIN>;
  chomp($user_end_hour);
  if($user_end_hour >= $log_start_hour && $user_end_hour <=
$log_end_hour) {
    $valid = 1;
  }
}

# Open up the log file again.
open(SYSLOG,$ifname) || die "ERROR: Unable to open input log file.\n";

# Start looping through the log file.
$start_found = 0;
while(<SYSLOG>) {

  $current_line = $_;
  split(/ {1,}/);
  $month = $months{$_[0]};
  $day = $_[1];
  $type = $_[4];
  $type =~ s/\[\w*\]://;
  $hour = (split(/:/,$_[2]))[0];

  # See if start point has been found.
  if($start_found == 0 && $month == $user_start_month && 
    $day == $user_start_day && $hour >= $user_start_hour) { 
    $start_found = 1;
  }

  # See if ending point has been reached.
  if($start_found && $month <= $user_end_month && $day <= $user_end_day
&&
    $hour <= $user_end_hour) {
    if($type eq $logtype) { print OUTPUT $current_line; }
  }
  else {
    close(SYSLOG);
    close(OUTPUT);
    exit(0);
  }

}


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

Date: Tue, 14 Apr 1998 20:23:00 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: perl's 'grep' vs. shell's 'grep'
Message-Id: <k521h6.29f.ln@localhost>

Pete Nelson (pete.nelson@ci.saint-paul.mn.us) wrote:
: Maybe I'm doing something wrong (always my first guess).

Good guess.

Not reading about grep when you want to use grep   ;-)


from 'perlfunc'

---------------------------------
=item grep BLOCK LIST

=item grep EXPR,LIST

This is similar in spirit to, but not the same as, grep(1)
and its relatives.  In particular, it is not limited to using
regular expressions.
---------------------------------

Note that Perl's grep() want a LIST as a second argument.

grep(1) wants a filename.


: From any unix shell, grep will spit out the line where the regexp is
: found, but perl 'grep' command would appear to be doing things a little
: different.  Am I best off calling 'grep' from /usr/bin with an 'exec'
: call?


Heavens no!

Don't fork off another process for something that can be done from
within Perl.

(exec() would not be the way to do it even if you do like to use up
 resources. You would use backticks ( qx// )
)


You can use something like:

--------------------------------
#!/usr/bin/perl -w

grep1('\b\w{4}\b', 'grep1');   # find four letter words in this file


sub grep1 {
   my($regex, $filename) = @_;

   open(IN, $filename) || die "could not open '$filename'  $!";

   while (<IN>) {    # read each line
      print if /$regex/;
   }
   close(IN);
}
--------------------------------


Or, if you have lots of memory, or small files:

sub grep1 {
   my($regex, $filename) = @_;

   open(IN, $filename) || die "could not open '$filename'  $!";

   print grep /$regex/, <IN>;  # reads the entire file into memory...

   close(IN);
}


--
    Tad McClellan                          SGML Consulting
    tadmc@metronet.com                     Perl programming
    Fort Worth, Texas


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

Date: 14 Apr 98 20:10:55 MDT
From: ronb@cc.usu.edu.I_e-bomb_your_provider (DR TE$TH & THE ELECTRIC MAYHEM)
Subject: Possible bug in dbm routine?!?!
Message-Id: <jjZfXfG4uwBs@cc.usu.edu>

I have a section of code that looks like:

dbmopen (%DB, "db.dbm", 0666);
while (($key, $val) = each %DB)
{
  print ("$key = $val\n");
}

For the same database, if I run this thing several times in succession, I get 8
lines one time, 4 the next, 6 the next, and so on.  What is going on?!?!?!

	rOn

--
Fone:801-787-8525  Page: 801-755-3746 - punch in your phone number and hit '#'
DISCLAIMER - These opoi^H^H "dang", ^H, [esc :q :qq !q "NYRGH!" :Q! "Whaddya
mean, Not an editor command?" :wq! ^C^C^C !STOP ^bye ^quit :quit! !halt ...
^w^q :!w :wq! ^D :qq!! ^STOP [HALT!   HALT!!! "Why's it doing this?" :stopit!
:wwqq!! ^Z ^L ^ESC STOP  :bye  bye  bye! M-X-DOCTOR "HELP! I can't get out of
this stupid editor!!!" And how does this make you feel?



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

Date: Tue, 14 Apr 1998 20:22:57 -0600
From: Dan Baker <dtbaker_@flash.net>
Subject: understanding Perl<->.html forms?
Message-Id: <35341A01.7F2@flash.net>

I've read a couple books already in an effort to gain a better
understanding of how to get data back and forth between Perl and .html
forms.... but I'm just not getting it very well. Does anyone know of a
good tutorial covering this topic for a beginner?

At the simplest level, I just want to use an .html form to save some
data to a local text file in win95 using perl to control the
manipulation. I don't even need to deal with web servers yet, I just
want to read/write to the local disk. I am a little confused on how to
approach programming a system where the scripts are not all in the same
program and the data may be acted on in a non-linear fashion depending
on what a user might call from the web interface.


Basically using html as an interface, and Perl as the glue. I'm having
trouble finding simple examples that:

- use an .html form to send data to a Perl script which writes data to a
file

- a perl script which reads data from a file, builds an .html page, and
then opens (or updates) a browser window.


any references I should go get? How about some simple examples?!

THANX, Dan

* remove the _ from my username to reply directly if desired.*


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

Date: 15 Apr 1998 02:21:27 GMT
From: "Dave Roth" <rothd@xrxoxtxhx.xnxextX>
Subject: Re: Win32:GetFreeDiskSpaceEx
Message-Id: <01bd6815$9f6cee00$0101a8c0@main2>



Thomas Nielsen <thn@ehs.dk> wrote in article
<353397be.0@mnemosyne.ehs.dk>...
> We have a slight problem here. We use the Cisco Resource
Manager, or rather
> mean to, but unfortunately they have chosen to use
GetDiskSpace() to
> retrieve disk information and thus fail to work on disks
larger than 2GB. I
> have found some modules which implement other routines,
such as admmisc by
> David Roth but as the Cisco software is fairly
comprehensive we are
> reluctant to include complete libraries, so as not to
introduce more points
> of error than are already there, but would rather get
around the problem by
> using the correct API. The problem is now that
GetFreeDiskSpaceEx() doesn't
> seem to work. First of all I need to pack and unpack
64bit integers
> (ULARGE_INTEGER) but I can't find any information as to
how to come about
> doing that. Secondly, I have no idea if this is the only
problem as I'm
> stranded already at the subject of packing. Does anyone
know how to use this
> API successfully with Perl? I just want the size and free
space of a disk or
> network drive above 7GB.

Go and grab Win32::AdminMisc from my ftp site.  Get the
source code and look in how I did it.  
I am just using:
  sprintf(szValue, "%I64u", ulTotalNumberOfBytes.QuadPart);
Then making a scalar that contains szValue.  It seems to
work fine.
Of course GetFreeDiskSpaceEx() is not supported on pre SR2
versions of Win95.  You need to check that you have SR2 and
if so then link to kernel32.dll and do a GetProcAddress()
to get a pointer to the function. If you are running only
on NT then don't worry about that crap. :)

dave
-- 
============================================================
====
Dave Roth                               ...glittering
prizes and
Roth Consulting                     endless compromises,
shatter
rxoxtxdxxrxoxtxhx.xnXeXt               the illusion of
integrity

 My email address is disguised to fool automailers. Remove
the
                      X's to send me email.
************************************************************
****
Use of  this message or  email address  for commercial 
purposes
(including "junk" mailings) is strictly prohibited and
protected
under  current  international  copyright laws  and United
States
Code, Title 47, Chapter 5, Subchapter II.




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

Date: 8 Mar 97 21:33:47 GMT (Last modified)
From: Perl-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 8 Mar 97)
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.misc (and this Digest), send your
article to perl-users@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.

The Meta-FAQ, an article containing information about the FAQ, is
available by requesting "send perl-users meta-faq". The real FAQ, as it
appeared last in the newsgroup, can be retrieved with the request "send
perl-users FAQ". Due to their sizes, neither the Meta-FAQ nor the FAQ
are included in the digest.

The "mini-FAQ", which is an updated version of the Meta-FAQ, is
available by requesting "send perl-users mini-faq". It appears twice
weekly in the group, but is not distributed in the digest.

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 V8 Issue 2323
**************************************

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