[17118] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4530 Volume: 9

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Oct 5 14:05:35 2000

Date: Thu, 5 Oct 2000 11:05:12 -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: <970769112-v9-i4530@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Thu, 5 Oct 2000     Volume: 9 Number: 4530

Today's topics:
    Re: a 14 day counter <jtjohnston@courrier.usherb.ca>
    Re: Common constants in a separate file <james@nospam.demon.co.uk>
        Does anyone have a jed mode for perl <anders@wall.alweb.dk>
    Re: error in mapping array slice <ren.maddox@tivoli.com>
    Re: how to unlink this file? (John J. Trammell)
    Re: how to unlink this file? (Gary E. Ansok)
    Re: How? Read a file from another server? (Clay Irving)
    Re: How? Read a file from another server? <godzilla@stomp.stomp.tokyo>
        HTML::Parser question (Ian Walker)
    Re: HTML::Parser question (Clay Irving)
    Re: HTML::Parser question <jeff@vpservices.com>
        Internet Website Survey Script <oneof1121@hotmail.com>
        LDAP-search recursing groups problem (Björn Nilsson)
    Re: Massive kill Unix and Perl <jeffp@crusoe.net>
        Not Entirely On Topic:  Programming and math <lmoran@wtsg.com>
    Re: Not Entirely On Topic:  Programming and math <bmb@ginger.libs.uga.edu>
        Perl newbie regex question <someone@somewhere.com>
    Re: Perl newbie regex question (Clay Irving)
    Re: Perl newbie regex question <sariq@texas.net>
    Re: Perl newbie regex question <yanick@babyl.sympatico.ca>
    Re: Perl newbie regex question <someone@somewhere.com>
    Re: Perl newbie regex question <ren.maddox@tivoli.com>
    Re: Perl newbie regex question <jeffp@crusoe.net>
    Re: perl variables <geva@electra-supply.com>
        Problem with SEEK and TELL within PERL objects <donv@webimpact.com>
        Re-Interpolating Variables <geva@electra-supply.com>
    Re: Re-Interpolating Variables (NP)
    Re: Re-Interpolating Variables <bcaligari@my-deja.com>
    Re: Re-Interpolating Variables <jeff@vpservices.com>
    Re: Reverse by paragraphs - NOT! <bmb@ginger.libs.uga.edu>
    Re: Reverse by paragraphs - NOT! (Anno Siegel)
    Re: Reverse by paragraphs - NOT! <lr@hpl.hp.com>
    Re: socket I/O <franl-removethis@world.omitthis.std.com>
        Stock market simulator cwiz@gdi.net
    Re: Stock market simulator <randy@theoryx5.uwinnipeg.ca>
    Re: URL Redirect <9jerry9@my-deja.com>
    Re: what on is correct??? <juex@deja.com>
        Writing to Excel 2000 hajir@my-deja.com
        Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)

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

Date: Fri, 06 Oct 2000 05:10:31 -0400
From: jtjohnston <jtjohnston@courrier.usherb.ca>
Subject: Re: a 14 day counter
Message-Id: <39DD9707.7072@courrier.usherb.ca>

> >Use Julian days and your life becomes simple.
> What is this "Julian Days" thing that keeps popping up? Why is it better
> than, say, days since Jan 1 1970?

Was there an answer since last night? I must be losing threads?
Could someone e-mail me?


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

Date: Thu, 5 Oct 2000 16:48:01 +0100
From: James Taylor <james@nospam.demon.co.uk>
Subject: Re: Common constants in a separate file
Message-Id: <ant0515010b0fNdQ@oakseed.demon.co.uk>

In article <Pine.GSO.4.21.0010050824430.14163-100000@crusoe.crusoe.net> japhy wrote:
> [posted & mailed]

I didn't get your mail Jeff and that's probably because I spamblock my
email address when posting to Usernet, sorry. I'll spell nospam in
CAPS in future.

Another problem is that Demon Internet's newsfeed does not seem to be
giving me any comp.lang.perl.misc articles [shock horror], which is
odd because it works fine for the other groups I'm on. I've double
checked my local configuration and it's correct so it must be a Demon
problem. I had to extract the text of your posting from DejaNews, so
I'm sorry if the lack of Referrer header mucks things up for everyone.

Your explanations were very helpful thank you.

> Here are a couple approaches:
> 
>   #!/usr/bin/perl
>   # main.pl
>   use strict;
>   use vars qw( $model );
>   require "values.pl";
>   print "Model: $model\n";
> 
> and:
> 
>   # values.pl  
>   $model = 'QRX-1800';

That's the one I like best because it most closely matches what I was
expecting to be able to do. I don't mind declaring the globals I'm
using with a "use vars qw()" and I can continue to interpolate the
constants into strings, etc. I'm not keen on the "use constant" method
because I lose that ability.

Clay Irving's suggestion of using App::Config is also interesting, but
I think I'll wait for a bigger project than these few simple scripts
to use it.

And to Michael Carman: thanks for the example code. I'll consult the
docs some time and practice writing modules.

-- 
James Taylor <james (at) oakseed demon co uk>
PGP key available ID: 3FBE1BF9
Fingerprint: F19D803624ED6FE8 370045159F66FD02



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

Date: Thu, 5 Oct 2000 17:23:12 +0200
From: Anders Lund <anders@wall.alweb.dk>
Subject: Does anyone have a jed mode for perl
Message-Id: <y21D5.1886$UW.68362@news010.worldonline.dk>

Does anyone have a jed mode for perl??

TIA,

-anders
-- 
[ the word wall - and the trailing dot - in my email address
is my _fire_wall - protecting me from the criminals abusing usenet]


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

Date: 05 Oct 2000 11:05:02 -0500
From: Ren Maddox <ren.maddox@tivoli.com>
Subject: Re: error in mapping array slice
Message-Id: <m3k8bne0k1.fsf@dhcp11-177.support.tivoli.com>

Tk Soh <r28629@email.sps.mot.com> writes:

> the original intention was to build an array from another with a minimum
> number of elements, or "pre-fill" with "" if element value is undefined.
> My two-line alternative works, but I thought using map would make the
> code more perl'ish:
> 
>    @this_array = map {defined? $_ : ''} @that_array[-10, -1];

My take on this is that you want to copy the last 10 elements of
@that_array into @this_array, but that if there are fewer than 10
elements in @that_array, then they should go at the end of
@this_array.

So if @that_array contains (1, 2, 3, 4, 5, 6), then after the copy
@this_array will contain (undef, undef, undef, undef, 1, 2, 3, 4, 5,
6).  Is that correct?

If so, then this should do it (though I certainly don't promise that
it is the *best* way):

@this_array = ((undef) x 10, @that_array)[-10 .. -1];

HTH,
-- 
Ren Maddox
ren@tivoli.com


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

Date: 5 Oct 2000 15:08:21 GMT
From: trammell@nitz.hep.umn.edu (John J. Trammell)
Subject: Re: how to unlink this file?
Message-Id: <slrn8toc34.qev.trammell@nitz.hep.umn.edu>

On Thu, 05 Oct 2000 14:32:38 GMT, bing-du@tamu.edu <bing-du@tamu.edu> wrote:
>I tried to use the following script to delete the
>file
>/usr/home/me/tmp/c24b18d4bb4afdf052330678af9a601d_attach_H:\tmp\zz.txt.
>
>===============
>#!/usr/local/bin/perl
>
>$tmp = "/usr/home/me/tmp";
>$uid = "c24b18d4bb4afdf052330678af9a601d";
>
>unlink("$tmp/$uid_attach_*") || die "file can not be deleted\n";
>exit;
>===============

Starting off with

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

should answer your question.

-- 
John J. Trammell
johntrammell@yahoo.com


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

Date: 5 Oct 2000 16:26:20 GMT
From: ansok@alumni.caltech.edu (Gary E. Ansok)
Subject: Re: how to unlink this file?
Message-Id: <8ria3c$fl4@gap.cco.caltech.edu>

In article <8ri3e6$4i1$1@nnrp1.deja.com>,  <bing-du@tamu.edu> wrote:
>===============
>#!/usr/local/bin/perl
>
>$tmp = "/usr/home/me/tmp";
>$uid = "c24b18d4bb4afdf052330678af9a601d";
>
>unlink("$tmp/$uid_attach_*") || die "file can not be deleted\n";
>exit;
>===============

There's a couple of problems with this:

1)  unlink doesn't take wildcards.  You'll need to get the exact name
of the file (probably using readdir or glob) to pass to unlink.

2)  You need to separate the variable name from the surrounding text.
There are a couple of ways to do this, but the simplest is probably
"$tmp/${uid}_attach_".

Some other suggestions:

3)  Use -w and strict.

4)  Change the die string to include $!, which will tell you why
the file could not be deleted.  In a short script like this it
may not matter, but in a longer script I would put the filename
in the die message, like "Cannot delete '$file': $!".

5)  You don't say whether this is a one-time action, or something
you'll need to do repeatedly, and we don't know what system(s) you
will need to run this on.  Assuming a Unix system, you might just 
want to use the "rm" program and shell wildcard processing -- 
system qq(rm "$tmp/${uid}_attach_*").  Sometimes it is simpler 
to use existing tools outside Perl.

-- Gary Ansok


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

Date: 5 Oct 2000 15:16:01 GMT
From: clay@panix.com (Clay Irving)
Subject: Re: How? Read a file from another server?
Message-Id: <slrn8tp6pg.r50.clay@panix2.panix.com>

On Thu, 05 Oct 2000 00:52:48 -0700, Godzilla! <godzilla@stomp.stomp.tokyo> 
wrote:

>>> The point is that you should *ALWAYS* check the result of open, like
>>> this:
>
>> > open (DATAFILE, "<$FileName") or die "Couldn't open file: $!";
>
>> Thanks very much for taking the time and effort to help me understand
>> this point.  It is greatly appreciated.

>There are better ways, more efficient ways to check
>not only a file open, but to also check for other
>errors as well. This standard issue Perl 5 Cargo
>Cultist *ALWAYS* do this is totally lame brain.

These statements simply are not true.

>Watch how a programmer handles this compared to
>these Perl 5 Copy & Paste Technicians.
>
>open (FILEHANDLE, "file.ext");
>@Array = <FILEHANDLE>;
>close (FILEHANDLE);
>
>if ($Array[$#Array] ne "my last element")
> { &Error_Handling; }
>
>For this example above, I know what my last
>element should be. This code of mine performs
>three tests; open file, array creation and,
>by inference, an uncorrupted array. This can
>be pinned down even better by hard coding in
>the last element reference number for a known
>created fixed array,
>
>if ($Array[86] ne "my known element")
> { &Blow_Up_My_Monitor; }
>
>
>Should I not know my last element,
>
>if (!(@Array))
> { &Error_Handling; }

Let me add to your program:

sub Error_Handling {
    print <<EOF;
The file open failed or something else happened, but I don't know why because
I didn't test the file open.
EOF
}

You imply your way is more efficient -- Let's test your theory. Start with
a test file:

  $ ls -l foo.txt
  -rw-------   1 clay     clay      1826231 Oct  5 07:01 foo.txt
  
Benchmark both methods:

  #!/usr/local/bin/perl
  
  use Benchmark;
  $count = 10;
  
  $t1 = timeit($count, '
  
      open F, "foo.txt" or die "Can not open foo.txt: $!\n";
  
  ');
  print "$count loops of doing it the right way took:",timestr($t1),"\n";
  
  
  $t2 = timeit($count, '
  
          open (G, "foo.txt");
          @Array = <G>;
          close (G);
          if (!(@Array)) 
            { print "Can not open foo.txt: I do not know why, though...\n"; }
  
      ');
  print "$count loops of doing it the retard way took:",timestr($t2),"\n";
  
  $ ./foo2.pl
  10 loops of doing it the right way took: 
  0 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
  10 loops of doing it the retard way took:
  13 wallclock secs ( 6.30 usr +  0.29 sys =  6.59 CPU) @  1.52/s (n=10)

You lose again troll...

--
Clay Irving <clay@panix.com>
Many of the truths we cling to depend greatly on our own point of view. 


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

Date: Thu, 05 Oct 2000 11:00:15 -0700
From: "Godzilla!" <godzilla@stomp.stomp.tokyo>
Subject: Re: How? Read a file from another server?
Message-Id: <39DCC1AF.475FEBE7@stomp.stomp.tokyo>

Clay Irving spewed vomitous verbal chunkies:
 
>  Godzilla! wrote an excellent article:

(snipped Irving idiocy logic)


> Many of the truths we cling to depend greatly on our own point of view.



"Truth is not what you make it to be. Truth makes what is to be."
  - Kira

* laughs *

You are so foolish to actually think I would
lend credibility to your mule manure.


Godzilla!
-- 
Dr. Kiralynne Schilitubi ¦ Cooling Fan Specialist
UofD: University of Duh! ¦ ENIAC Hard Wiring Pro
BumScrew, South of Egypt ¦ HTML Programming Class


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

Date: Thu, 05 Oct 2000 16:16:59 GMT
From: ian.walker@homme.com (Ian Walker)
Subject: HTML::Parser question
Message-Id: <39dca504.98833755@news>

I have tried to RTFM and after alot of looking I still don't get it...

what I have is a variable, we will call it, $html_here
in that variable is an entire html file, i was told that HTML::Parser
can split the file up into sections separated by the tags, and clean
up all tags. So <img 
xyz>

will become <img xyz>  (no carage return).

so is it possible to take $html_here and output it to a new variable
all cleaned up??

Thanks for any info.

--
please remove the middle letter in the word homme in my email address.







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

Date: 5 Oct 2000 16:41:22 GMT
From: clay@panix.com (Clay Irving)
Subject: Re: HTML::Parser question
Message-Id: <slrn8tpbph.kr6.clay@panix2.panix.com>

On Thu, 05 Oct 2000 16:16:59 GMT, Ian Walker <ian.walker@homme.com> wrote:

>I have tried to RTFM and after alot of looking I still don't get it...
>
>what I have is a variable, we will call it, $html_here
>in that variable is an entire html file, i was told that HTML::Parser
>can split the file up into sections separated by the tags, and clean
>up all tags. So <img 
>xyz>
>
>will become <img xyz>  (no carage return).
>
>so is it possible to take $html_here and output it to a new variable
>all cleaned up??

I don't know... What did you try and what happened?

-- 
Clay Irving <clay@panix.com>
When I was little, my grandfather used to make me stand in a closet for
five minutes without moving. He said it was elevator practice.
- Steven Wright 


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

Date: Thu, 05 Oct 2000 10:45:03 -0700
From: Jeff Zucker <jeff@vpservices.com>
Subject: Re: HTML::Parser question
Message-Id: <39DCBE1F.F3EBDDE5@vpservices.com>

Ian Walker wrote:
> 
> I have tried to RTFM and after alot of looking I still don't get it...
> 
> what I have is a variable, we will call it, $html_here
> in that variable is an entire html file, i was told that HTML::Parser
> can split the file up into sections separated by the tags, and clean
> up all tags. So <img
> xyz>
> 
> will become <img xyz>  (no carage return).
> 
> so is it possible to take $html_here and output it to a new variable
> all cleaned up??

The part you are probably missing is that HTML::Parser uses callbacks. 
This means that *you* create a series of routines to define what happens
when the parser encounters a certain kind of event (e.g. when the parser
gets to the start of a tag).  Then you feed the parser a string or file
and it calls back (get it? :-)) those routines you defined when it gets
to the various  events associated with them.

To do the kind of thing you are trying to do, you might be best off with
using the HTML::Filter module that comes with HTML::Parser.  All you'd
need to do would be to redefine the output() method to strip returns
before printing, and/or to have it build up a new variable rather than
printing.  It takes about half a dozen lines of code to build the kind
of tidier you have requested.

You might also wish to see Jonathan Stowe's excellent set of examples
at:

    http://www.gellyfish.com/htexamples/

P.S. No biggy, but in the future this kind of question might be better
off in comp.lang.perl.modules since your question deals specifically
with the use of the module.

-- 
Jeff


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

Date: Thu, 05 Oct 2000 12:18:59 -0500
From: beggar <oneof1121@hotmail.com>
Subject: Internet Website Survey Script
Message-Id: <nudptsobmi0c9n73pd1av74c9qp6f0uvsl@4ax.com>

Can someone recommend a survey script?


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

Date: Thu, 05 Oct 2000 15:20:45 GMT
From: bjorn.nilsson@bct.ericsson.se (Björn Nilsson)
Subject: LDAP-search recursing groups problem
Message-Id: <39dc9b81.24884451@news.ericsson.se>

Hi all!

I'm trying to modify the printMembers.pl script (which is included in
the Example subdir of the distribution of the LDAP module) to suit my
needs. 
My problem is that the script doesn't resolve the sublists at all, or
that it just resolve the first member of a sublist. 
What I want is to get each and every members (person) attributes to
insert them into another database, grouped by the mailinglist in
question.

What I do is:

#!/usr/local/bin/perl

use Net::LDAP qw(:all);

$cnt = 0;
# the connection to the ldap server is configured here
$server = "an_exchangeserver.ericsson.se";
$port = getservbyname("ldap", "tcp") || "389";
$basedn = "o=ericsson";
$scope = "base";
$which = "AXE Swingers"; 
# No, there is no group in ericsson with that name :-)

# escape ( and ) if present
$which =~ s/\(/\\(/g;
$which =~ s/\)/\\)/g;

$c = new Net::LDAP($server) 
	or die "Unable to connect to $server: $@\n";

$c->bind() or die "Unable to bind: $@\n";

my @attrs = ['dn', 'objectClass', 'member'];

eval
{
	my $searchobj = $c->search(
					base => $basedn, 
					scope => $scope, 
					filter =>
"(&(cn=$which)(objectClass=groupOfNames) )", 
					#attrs => @attrs 
					);
	die "Bad search, errorcode #" . $searchobj->code() 
		if $searchobj->code();	
	my $entry = $searchobj->pop_entry();	
	my $groupDN = $entry->dn();	
	&printMembers($groupDN);
};

$c->unbind();

sub printMembers
{
	my $dn = @_[0];
	print "\t$dn\n";
	my @attrs = ['dn', 'member'];
	my $searchobj = $c->search(
		base => $dn,
		scope => 'base',
		filter => "objectClass=*",
		#attrs => @attrs
		);
	die $searchobj->error if $searchobj->code;
#	eval
#	{		
#	foreach $entry2 ($searchobj->all_entries) { $entry2->dump; }
#	};

	
	eval
	{
		# should only be one entry
		my $entry = $searchobj->pop_entry();		
		print "\nMembers of group: $dn\n";		
		# returns an array reference
		my $values = $entry->get("member");
		
		foreach my $val ( @{$values} )
		{
			print "$val\n";
			my $isGroup = 0; 
		#Lets us know if the entry is also a group, 
		#default no.
		# my @entryAttrs = ["objectClass", "member", "cn"];
			
			$mesg = $c->search(
					base => $val,
					scope => 'base',
					filter => "objectClass=*",
					#attrs => @entryAttrs
						);
			die $mesg->error if $mesg->code;
	#foreach $entry2 ($mesg->all_entries) { $entry2->dump; }
			eval
			{
				my $entry = $mesg->pop_entry();
				#if ($attr)
				#{
				#	my $values =
$entry->get($attr);
				#	foreach my $vals ( @{$values}
)
				#	{
				#		print $vals . "\n";
				#	}	
				#}
				#else
				#{
					print "$val\n";
				#}
				
				my $values =
$entry->get("objectClass");
				# This value is also a group, 
				# print the members of it as well
				
				&printMembers($entry->dn(), $attr) if
(grep /groupOfNames/i, @{$values} );
			};				
		}
	};
	return 0;
}


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

Date: Thu, 5 Oct 2000 13:11:17 -0400
From: Jeff Pinyan <jeffp@crusoe.net>
Subject: Re: Massive kill Unix and Perl
Message-Id: <Pine.GSO.4.21.0010051309590.14163-100000@crusoe.crusoe.net>

On Oct 5, Graham Daniell said:

>If you had said RTFM I would have understood.  I thought that there was
>some wonderful resource out there that I was  missing out on!!! (:-)>

Would not a series of books on programming languages, called the "TFM
series", be a wonderful addition to our literature?  Of course, for Perl,
that would be a tome of great mass, but still.

  "TFM: Lisp"
  "TFM: Perl"
  "TFM: C"

Et cetera.  I'd like it. :)

-- 
Jeff "japhy" Pinyan     japhy@pobox.com     http://www.pobox.com/~japhy/
PerlMonth - An Online Perl Magazine            http://www.perlmonth.com/
The Perl Archive - Articles, Forums, etc.    http://www.perlarchive.com/
CPAN - #1 Perl Resource  (my id:  PINYAN)        http://search.cpan.org/





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

Date: Thu, 05 Oct 2000 13:21:41 -0400
From: Lou Moran <lmoran@wtsg.com>
Subject: Not Entirely On Topic:  Programming and math
Message-Id: <35eptscl81drjr8gn9teh5ol2a2p00gcql@4ax.com>

--Is a strong background in mathematics (not arithmetics) mandatory
for a successful career as a programmer?

--Could a creative (musician/writer/painter/whatever) person become a
"real" (read useful/good/paid) programmer without having mathematical
prowess?


PS -- My brain stopped accepting math around quadratic equations




"Well that it explains it fish-bulb"
Registered Linux user number 187055


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

Date: Thu, 5 Oct 2000 13:37:46 -0400
From: Brad Baxter <bmb@ginger.libs.uga.edu>
Subject: Re: Not Entirely On Topic:  Programming and math
Message-Id: <Pine.A41.4.21.0010051337290.12502-100000@ginger.libs.uga.edu>

On Thu, 5 Oct 2000, Lou Moran wrote:

> --Is a strong background in mathematics (not arithmetics) mandatory
> for a successful career as a programmer?
> 
> --Could a creative (musician/writer/painter/whatever) person become a
> "real" (read useful/good/paid) programmer without having mathematical
> prowess?
> 
> 
> PS -- My brain stopped accepting math around quadratic equations

How are you with word problems?

Brad



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

Date: Thu, 05 Oct 2000 12:03:05 -0400
From: Sgb <someone@somewhere.com>
Subject: Perl newbie regex question
Message-Id: <n39ptsk8qpnofrct7903qcf6ks35p83om3@4ax.com>

I'm very new to Perl still, trying to figure out a regex thing.

I have a variable which contains a full pathname, such as:
$full_path = "/drive1/big/long/path/myfile.txt"
What I have to do is pull just the filename and assign it to another
variable. I want to end up with:
$filename = "myfile.txt"
The only thing I can figure is somehow search beginning from the end
(right) of the variable. Search until the first forward-slash is
found, and then stop, but I have no idea how that would work.

Could anyone help me put something together that might do this?




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

Date: 5 Oct 2000 16:15:29 GMT
From: clay@panix.com (Clay Irving)
Subject: Re: Perl newbie regex question
Message-Id: <slrn8tpa91.h0g.clay@panix2.panix.com>

On Thu, 05 Oct 2000 12:03:05 -0400, Sgb <someone@somewhere.com> wrote:

>I'm very new to Perl still, trying to figure out a regex thing.
>
>I have a variable which contains a full pathname, such as:
>$full_path = "/drive1/big/long/path/myfile.txt"
>What I have to do is pull just the filename and assign it to another
>variable. I want to end up with:
>$filename = "myfile.txt"
>The only thing I can figure is somehow search beginning from the end
>(right) of the variable. Search until the first forward-slash is
>found, and then stop, but I have no idea how that would work.
>
>Could anyone help me put something together that might do this?

An easy way:

  #!/usr/local/bin/perl

  use File::Basename;

  $full_path = "/drive1/big/long/path/myfile.txt";

  ($filename, $path, $suffix) = fileparse($full_path);

  print "$filename\n";

Result:

  myfile.txt

-- 
Clay Irving <clay@panix.com>
If you wish to appear agreeable in society, you must consent to be taught
many things which you know already. 
- Johann Kaspar Lavater 


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

Date: Thu, 05 Oct 2000 16:15:46 GMT
From: Tom Briles <sariq@texas.net>
Subject: Re: Perl newbie regex question
Message-Id: <39DCA932.9408BAA4@texas.net>

Sgb wrote:
> 
> I'm very new to Perl still, trying to figure out a regex thing.
> 
> I have a variable which contains a full pathname, such as:
> $full_path = "/drive1/big/long/path/myfile.txt"
> What I have to do is pull just the filename and assign it to another
> variable. I want to end up with:
> $filename = "myfile.txt"

perldoc File::Basename

You can look at Basename.pm if you're curious about the implementation.

- Tom


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

Date: Thu, 05 Oct 2000 16:35:26 GMT
From: Yanick Champoux <yanick@babyl.sympatico.ca>
Subject: Re: Perl newbie regex question
Message-Id: <i52D5.1316$px1.23372@news20.bellglobal.com>

Sgb <someone@somewhere.com> wrote:
: I'm very new to Perl still, trying to figure out a regex thing.

: I have a variable which contains a full pathname, such as:
: $full_path = "/drive1/big/long/path/myfile.txt"
: What I have to do is pull just the filename and assign it to another
: variable. I want to end up with:
: $filename = "myfile.txt"
: The only thing I can figure is somehow search beginning from the end
: (right) of the variable. Search until the first forward-slash is
: found, and then stop, but I have no idea how that would work.

: Could anyone help me put something together that might do this?

You probably want to have a look at 'perldoc perlre'. 

In the meantime, a way of doing what you want would be

$file = $full_path;
$file =~ s#^.*/##;		# delete everything up to the last /
                        
or

$full_path =~ m#([^/]*)$#;  # slurp anything slashes from right-side
$file = $1;

or (this is getting gonzo)

$file = ( split '/', $full_path )[-1];

or (this is even worse)

( $file ) = reverse ( split '/', $full_path );

or even

$file = $full_path;
1 while $file =~ s#[^/](?=/)#/#;
$file =~ tr#/##d;

Hum. Okay, I'll stop here.

Joy,
Yanick

-- 
($_,$y)=("Yhre lo  .kePnarhtretcae\n",   '(.) (.)'  );
$y=~s/\(/(./gwhile s/$y/$2$1/xg;print;       @      !; 
                                     "     `---'    ";


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

Date: Thu, 05 Oct 2000 13:12:03 -0400
From: Sgb - Thanks all! <someone@somewhere.com>
Subject: Re: Perl newbie regex question
Message-Id: <7gdpts0i17q9qnbau9eo8lc5na0dkgvg62@4ax.com>

Thanks a bunch for all the quick replies. Got everything working great
thanks to your help.



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

Date: 05 Oct 2000 11:43:40 -0500
From: Ren Maddox <ren.maddox@tivoli.com>
Subject: Re: Perl newbie regex question
Message-Id: <m38zs3dyrn.fsf@dhcp11-177.support.tivoli.com>

Sgb <someone@somewhere.com> writes:

> I'm very new to Perl still, trying to figure out a regex thing.
> 
> I have a variable which contains a full pathname, such as:
> $full_path = "/drive1/big/long/path/myfile.txt"
> What I have to do is pull just the filename and assign it to another
> variable. I want to end up with:
> $filename = "myfile.txt"
> The only thing I can figure is somehow search beginning from the end
> (right) of the variable. Search until the first forward-slash is
> found, and then stop, but I have no idea how that would work.

I've already seen several responses that give you alternate ways to do
this, but I just wanted to point out that they way you have proposed
will work fine (though not as portable as the File::Basename
solution).

#!/usr/local/bin/perl -w
use strict;
my $full_path = "/drive1/big/long/path/myfile.txt";
my $filename = substr($full_path, rindex($full_path, "/") + 1);
print $filename, "\n";
__END__


For more information:

perldoc -f rindex
perldoc -f substr

-- 
Ren Maddox
ren@tivoli.com


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

Date: Thu, 5 Oct 2000 13:28:10 -0400
From: Jeff Pinyan <jeffp@crusoe.net>
Subject: Re: Perl newbie regex question
Message-Id: <Pine.GSO.4.21.0010051325230.14163-100000@crusoe.crusoe.net>

[posted & mailed]

On Oct 5, Sgb said:

>$full_path = "/drive1/big/long/path/myfile.txt"
>$filename = "myfile.txt"

>The only thing I can figure is somehow search beginning from the end
>(right) of the variable. Search until the first forward-slash is
>found, and then stop, but I have no idea how that would work.

Yes, you should use File::Basename.  But to answer your general question,
if you want the last occurrence of non-X characters in a string, you
should use:

  ($last) = $string =~ /([^X]*)$/;

That will match 0 or more non-X characters followed by end-of-string.

Or use sexeger.  But that's too much for this case.  Or is it...?

  http://www.pobox.com/~japhy/sexeger/sexeger.html

-- 
Jeff "japhy" Pinyan     japhy@pobox.com     http://www.pobox.com/~japhy/
PerlMonth - An Online Perl Magazine            http://www.perlmonth.com/
The Perl Archive - Articles, Forums, etc.    http://www.perlarchive.com/
CPAN - #1 Perl Resource  (my id:  PINYAN)        http://search.cpan.org/





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

Date: Thu, 5 Oct 2000 10:52:31 -0400
From: "Greg Eva" <geva@electra-supply.com>
Subject: Re: perl variables
Message-Id: <8ri4kv$6cg$1@cougar.golden.net>


"web" <swebster@telnet.ca> wrote in message
news:hs_C5.35953$Z2.521632@nnrp1.uunet.ca...
> Can i create a variable with a value that has a space between characters?
> eg. $fromaddr = $in{'E-mail Address'};
>
> Or does it all have to be one word?
> cheers
>

Why not try it?  To answer your question though.. yes.




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

Date: Thu, 05 Oct 2000 13:11:38 -0400
From: Don Vaillancourt <donv@webimpact.com>
Subject: Problem with SEEK and TELL within PERL objects
Message-Id: <39DCB64A.81229084@webimpact.com>

Has anyone had problems using such functions as SEEK and TELL within a
PERL subroutine that belongs to an object.

I have no problem using READ and PRINT, but SEEK always returns 1 even
if it should be failing, and TELL always returns 0 when the file is
clearly no empty.

Any clues, please help.

Don



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

Date: Thu, 5 Oct 2000 10:57:29 -0400
From: "Greg Eva" <geva@electra-supply.com>
Subject: Re-Interpolating Variables
Message-Id: <8ri4u9$6h1$1@cougar.golden.net>

I need help.  I could also use some assistance with a Perl problem me and
myself are having.  I am looking to interpolate variable from a string..
this sounds general.

To be more specific, if you created something like..

$name = "Frankie";
$mesg = "$name is insane!\n";

This works fine, because it interpolates when it is setting $mesg.  But wht
I want to do is interpolate something that I am inputting.  For instance
from a file.  Pull in a string from a file, and have Perl interpolate a
variable name that I have stragically place in the file.

Hope someone can help, as this would simplify our work much.

Greg




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

Date: Thu, 05 Oct 2000 15:26:58 GMT
From: nvp@spamnothanks.speakeasy.org (NP)
Subject: Re: Re-Interpolating Variables
Message-Id: <651D5.5386$UP5.73225@news6.giganews.com>

geva@electra-supply.com wrote:
: 
: This works fine, because it interpolates when it is setting $mesg.  But wht
: I want to do is interpolate something that I am inputting.  For instance
: from a file.  Pull in a string from a file, and have Perl interpolate a
: variable name that I have stragically place in the file.

There are several ways that you can do this.

First, I believe that Text::Template can handle what you propose.

Or, if I understand your question correctly, you have a text file that
looks like this:

$ cat /tmp/interp.txt
The value of \$foo is a $foo.

And this line doesn't contain any variables.

Well, $name, thanks for playing!

<EOF>

And you want the strings $foo and $name to be replaced with the values
of $foo and $name.

I believe that this code should help you out.

#!/usr/bin/perl -w

my $name = "Nate";
my $foo = "blah blah";

open(IN, "/tmp/interp.txt")
    or die("can't open $file: $!");
my @lines = <IN>;
close(IN);

foreach my $line (@lines) {
    chomp($line);
    print eval "qq[$line]","\n";
}

This outputs:

The value of $foo is a blah blah.

And this line doesn't contain any variables.

Well, Nate, thanks for playing!

-- 
Nate II


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

Date: Thu, 05 Oct 2000 15:43:16 GMT
From: Brendon Caligari <bcaligari@my-deja.com>
Subject: Re: Re-Interpolating Variables
Message-Id: <8ri7ii$8gq$1@nnrp1.deja.com>

In article <8ri4u9$6h1$1@cougar.golden.net>,
  "Greg Eva" <geva@electra-supply.com> wrote:
> I need help.  I could also use some assistance with a Perl problem me
and
> myself are having.  I am looking to interpolate variable from a
string..
> this sounds general.
>
> To be more specific, if you created something like..
>
> $name = "Frankie";
> $mesg = "$name is insane!\n";
>
> This works fine, because it interpolates when it is setting $mesg.
But wht
> I want to do is interpolate something that I am inputting.  For
instance
> from a file.  Pull in a string from a file, and have Perl interpolate
a
> variable name that I have stragically place in the file.
>
> Hope someone can help, as this would simplify our work much.
>
> Greg
>
>

how about using regex substitutions?

suppose you have read a line into scalar, say $sharmuta

$sharmuta may contain a stirng, say <myname>

you would want to replace all instances of <myname> in
$sharmuta with scalar $realname

you could use something like

$sharmuta =~ s/<myname>/$realname/g;

brendon
++++



Sent via Deja.com http://www.deja.com/
Before you buy.


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

Date: Thu, 05 Oct 2000 08:59:57 -0700
From: Jeff Zucker <jeff@vpservices.com>
Subject: Re: Re-Interpolating Variables
Message-Id: <39DCA57D.79898054@vpservices.com>

Greg Eva wrote:
> ...
> This works fine, because it interpolates when it is setting $mesg.  But wht
> I want to do is interpolate something that I am inputting.  For instance
> from a file.  Pull in a string from a file, and have Perl interpolate a
> variable name that I have stragically place in the file.

See the section of perlfaq4 titled:

	"How can I expand variables in text strings?"

-- 
Jeff


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

Date: Thu, 5 Oct 2000 11:35:34 -0400
From: Brad Baxter <bmb@ginger.libs.uga.edu>
Subject: Re: Reverse by paragraphs - NOT!
Message-Id: <Pine.A41.4.21.0010051130580.12502-100000@ginger.libs.uga.edu>

On Thu, 5 Oct 2000 ollie_spencer@my-deja.com wrote:
> Whoops, I'm getting technical. Perhaps you aren't ready for that. I
> don't exactly have your credentials.

Good grief, Ollie.  You've gotten at least half a dozen bits of code that
will solve your problem.  I base that statement on the fact that you have
successfully written an intermediate file that can be processed by reading
it in paragraph mode.  If you can do the one, you can to the other using
code you've been generously supplied.

Brad



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

Date: 5 Oct 2000 15:36:13 -0000
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: Reverse by paragraphs - NOT!
Message-Id: <8ri75d$dcv$1@lublin.zrz.tu-berlin.de>

<ollie_spencer@my-deja.com> wrote in comp.lang.perl.misc

[de-jeopardized]

> In article <8rhkbf$aul$1@lublin.zrz.tu-berlin.de>,
>   anno4000@lublin.zrz.tu-berlin.de (Anno Siegel) wrote:
> >  <ollie_spencer@my-deja.com> wrote in comp.lang.perl.misc, still
> stubbornly
> > posting jeopardy style:
> >
> > >Thanks for the reply. I believe you might actually have read my
> original
> > >posting! Many seem to have not.
> >
> > Did you read the replies you got?
> >
> > >Thanks again! I'll post my results-I never thought to slurp a para
> at a
> > >time!
> >
> > How about the half-dozen or so postings that suggested just that?
> >
> > Anno
> Thanks for the posting. I think.
> 
> Yes, I read each made to me, reserving first priority to those that
> were are on subject.

Well, if you get a noticeable number of replies that you judge "off
subject", chances are that you didn't make your subject very clear
in the first place.  Do you really think people are replying to
messages they haven't read just for the heck of it?  Exceptions granted,
a poster who replies to you has made a serious effort to understand
what you are up to.  One or the other may have given up in frustration,
leading to what you perceive to be "person(al) attacks".  Others may
have honestly failed to get what you want, but if that happens a number
of times, who, do you think, is to blame?

>                       Second priority went to those that prefer person
> attacks to technical input ( like this one) and after that, I don't
> even read Godzilla's works of fiction.

[...]

> I can only post in mornings and evenings- sometimes at lunch or breaks-
> since my I have committments to my employer.

Whatever your posting habits and restrictions, it is up to you to
make sure you know the thread you are commenting on.

[...]

> If you feel I have overlooked someone, or a point made by some previous
> poster, please be specific - I will reread it and see if I agree.

Okay, here goes.  These have all suggested processing the file as a list
of paragraphs:

   From: nvp@spamnothanks.speakeasy.org (NP)
   Date: Mon Oct 02 18:50:57 MEST 2000
   $/ = '';

   From: amonotod <amonotod@netscape.net>
   Date: Mon Oct 02 19:23:31 MEST 2000
   @paras = split(/\n\n/, $article);
   
   From: Ren Maddox <ren.maddox@tivoli.com>
   Date: Tue Oct 03 07:09:51 MEST 2000
   $/ = "";   # or "\n\n" if you don't want to ignore extra blank lines

   From: michel.dalle@usa.net (Michel Dalle)
   Date: Wed Oct 04 16:59:42 MEST 2000
   So if your original array contains paragraphs as elements and you
   reverse the array, you will get the paragraphs in reverse.

   From: Uri Guttman <uri@sysarch.com>
   Date: Wed Oct 04 17:21:42 MEST 2000
   try File::ReadBackwards and set the input record separator to "\n\n".

   From: michel.dalle@usa.net (Michel Dalle)
   Date: Thu Oct 05 12:28:11 MEST 2000
   A better approach would be to make sure you fill your
   original array directly with paragraphs instead of lines.

   From: Bart Lateur <bart.lateur@skynet.be>
   Date: Wed Oct 04 21:12:56 MEST 2000
   I feel the same whay too. So, let's try to turn the array of lines into
   an array of paragraphs.

   From: Bart Lateur <bart.lateur@skynet.be>
   Date: Mon Oct 02 23:10:50 MEST 2000
   local $/ = '';

   From: Brad Baxter <bmb@ginger.libs.uga.edu>
   Date: Mon Oct 02 23:25:32 MEST 2000
   You say that the paragraphs are stored in @OF, but it looks to me like
   you're storing lines there.  Take a look at the $/ variable (perldoc
   perlvar).  Setting it to "" will let you read your file paragraph by
   paragraph.

   From: "Andrew N. McGuire " <anmcguire@ce.mediaone.net>
   Date: Thu Oct 05 01:34:46 MEST 2000
   $/ = q++;

   From: stdenton@my-deja.com
   Date: Wed Oct 04 19:56:17 MEST 2000
   $/ = '';  # slurp in a para at a time

This is what I gather from a cursory overview of the thread.  So you
managed not to get the hint in at least 10 cases.  *You* complain
about people not reading your posts?

> A personal note ( since this reply is to an attack on me):
> I have been using interpretive languages in my engineering work since

[more "credentials" snipped]

> Whoops, I'm getting technical. Perhaps you aren't ready for that. I
> don't exactly have your credentials.

 ...and I'm not going to list them for you.  Check some of my postings
and judge yourself the level of my expertise.  Since you're posting
from deja, that shouldn't be so hard.

I advise you to go back to lurking.  With your attitude you're not
going to find much joy in active posting.

Anno


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

Date: Thu, 5 Oct 2000 10:48:17 -0700
From: Larry Rosler <lr@hpl.hp.com>
Subject: Re: Reverse by paragraphs - NOT!
Message-Id: <MPG.14465ebc74cacd2898ae0c@nntp.hpl.hp.com>

In article <8ri75d$dcv$1@lublin.zrz.tu-berlin.de> on 5 Oct 2000 15:36:13 
-0000, Anno Siegel <anno4000@lublin.zrz.tu-berlin.de> says...

 ...

>    From: "Andrew N. McGuire " <anmcguire@ce.mediaone.net>
>    Date: Thu Oct 05 01:34:46 MEST 2000
>    $/ = q++;

That reminds me to offer a tip of the hat to Andrew N. McGuire for a 
clever bit of obfuscation.  At first glance, I wondered what in hell the 
fragment of C code incrementing the variable 'q' was doing in there.

-- 
(Just Another Larry) Rosler
Hewlett-Packard Laboratories
http://www.hpl.hp.com/personal/Larry_Rosler/
lr@hpl.hp.com


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

Date: Thu, 5 Oct 2000 17:15:24 GMT
From: Francis Litterio <franl-removethis@world.omitthis.std.com>
Subject: Re: socket I/O
Message-Id: <m31yxvb45v.fsf@franl.andover.net>

Uri Guttman <uri@sysarch.com> writes:

> i have never called shutdown on a socket. and calling after closing
> the socket makes no sense. just use close. it works.

It works, but close can sometimes work differently than shutdown.  From
"perldoc -f shutdown":

    This is useful with sockets when you want to tell the other
    side you're done writing but not done reading, or vice versa.
    It's also a more insistent form of close because it also
    disables the filedescriptor in any forked copies in other
    processes.
--
Francis Litterio
franl-removethis@world.std.omit-this.com
PGP public keys available on keyservers.


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

Date: Thu, 05 Oct 2000 14:58:24 GMT
From: cwiz@gdi.net
Subject: Stock market simulator
Message-Id: <8ri4u9$63c$1@nnrp1.deja.com>

Hi all,

I would like to create a fictitious stock market exchange on a website,
where users buy and sell stocks of imaginary companies.  Are there any
already available Perl scripts that do this sort of simulation?

Thanks in advance!

Wisam


Sent via Deja.com http://www.deja.com/
Before you buy.


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

Date: 5 Oct 2000 17:22:26 GMT
From: Randy Kobes <randy@theoryx5.uwinnipeg.ca>
Subject: Re: Stock market simulator
Message-Id: <8ridci$1rq$1@canopus.cc.umanitoba.ca>

In comp.lang.perl.misc, cwiz@gdi.net wrote:

> I would like to create a fictitious stock market exchange on a website,
> where users buy and sell stocks of imaginary companies.  Are there any
> already available Perl scripts that do this sort of simulation?

Here's a script that might help in putting something like this 
together - it simulates, on a crude level, the observed 
fluctuations in a stock price.

best regards,
randy kobes

##################################################
#!/usr/bin/perl -w
use strict;
#
# $rate (0 < $rate < 4) controls the rate of change of the price
#
my $rate = 3.98; 
#
# future prices will be stored in the @price array,
# where the array index 0 ... $max_time denotes the time
# (this can be in seconds, days, months, years, ...).
# All prices are between 0 and 1; scale as desired.
# $max_time is the maximum time; $initial_price is the initial price.
#
my $initial_price = 0.7;
my $max_time = 20;
#
# get the array with future prices
my @price = logistic($rate, $initial_price, $max_time);
#
# print it out
for (my $k = 0; $k <= $max_time; $k++) {
    print "time: $k \t price: $price[$k]\n";
}
# routine to calculate future prices
sub logistic {
  my ($mu, $xstart, $N) = @_;
  my @x;
  $x[0] = $xstart;
  for (my $n = 0; $n < $N; $n++) {
    $x[$n+1] = $mu * $x[$n] * (1 - $x[$n]);
  }
  return @x;
}
################################################


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

Date: Thu, 05 Oct 2000 17:04:38 GMT
From: Jerry Leventer <9jerry9@my-deja.com>
Subject: Re: URL Redirect
Message-Id: <8ricb3$cq8$1@nnrp1.deja.com>

Create an html file at the URL that you want to redirect FROM with
something like the following:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
  <HTML>
  <HEAD>
  <META HTTP-EQUIV="Refresh"  CONTENT="0;
URL=http://redirect_to_your_site.com/your_file.htm">
  </HEAD>
  </HTML>

In article <8qq6lh$fi6$1@gxsn.com>,
  "Keat" <Keat@beal.org.uk> wrote:
> I'm looking for a perl script that will automatically open up another
url
> when exiting the original,  I know its possible as I've seen it done
on the
> xxx sites, but I cant seem to find a script anywhere. Does anyone have
any
> ideas where I can find such a script....????
>
> Please reply to keat@beal.org.uk
> Keaton Roebuck
>
>


Sent via Deja.com http://www.deja.com/
Before you buy.


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

Date: Thu, 5 Oct 2000 10:22:48 -0700
From: "Jürgen Exner" <juex@deja.com>
Subject: Re: what on is correct???
Message-Id: <39dcb882@news.microsoft.com>

"Tigz" <tigz@ntlworld.com> wrote in message
news:j%DC5.12453$L12.251687@news2-win.server.ntlworld.com...
> Hi could someone tell me which is correct, both seem to work fine, but i
am
> not sure. I actually dont have a clue what i am doing... I am just trying
to
> lern....

Well, "correct" is a relative term. You can show (or sometimes even prove)
that a program is correct WITH RESPECT TO A GIVEN SPECIFICATION.
Unfortunately you didn't give us any clue as to what the program is supposed
to do, in so far we have no way of comparing the actual behaviour to the
expected behaviour.

Hint: Compare what happens if $testver is negative. If you can prove that
$testver will never be negative then the two programs are identical.

jue




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

Date: Thu, 05 Oct 2000 15:45:08 GMT
From: hajir@my-deja.com
Subject: Writing to Excel 2000
Message-Id: <8ri7m2$8ji$1@nnrp1.deja.com>

I am trying to write into an Excel 2000 cell using this, but I get an
error:  Can't Call Method Workbooks .  I also get a can't call method
Range for another one.  Please help


        use OLE;
        $excel = CreateObject OLE 'Excel.Application.5'
               or warn "Couldn't create new instance of Excel App!!";
        $excel->Workbooks->Open( 'test.xls' );
        $excel->Workbooks(1)->Worksheets('Sheet1')->Cells(1,2)->{Value}
= 'foo';
        $excel->Workbooks(1)->Worksheets('Sheet1')->Cells(1,2)->{Value}
= 'bar';
        $excel->Save();
        $excel->Quit();


Sent via Deja.com http://www.deja.com/
Before you buy.


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

Date: 16 Sep 99 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 16 Sep 99)
Message-Id: <null>


Administrivia:

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

| NOTE: The mail to news gateway, and thus the ability to submit articles
| through this service to the newsgroup, has been removed. I do not have
| time to individually vet each article to make sure that someone isn't
| abusing the service, and I no longer have any desire to waste my time
| dealing with the campus admins when some fool complains to them about an
| article that has come through the gateway instead of complaining
| to the source.

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 V9 Issue 4530
**************************************


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