Re: First-time forking

2006-03-13 Thread Shawn Corey

Cornelis Swanepoel wrote:

The SIG{CHLD} handler doesn't get called since the output from


print LOG Child process no. $stiff exited with status $?\n;


is missing.


It's not missing; it was never there. Your parent process dies before 
its children are finished. It is no longer around to reap the status of 
their execution. You would have to add a wait loop at the end of your 
program.


# untested
  while( ( my $child_pid = wait ) != -1 ){
  }

See `perldoc -f wait` and `perldoc perlipc` for details.

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Padded 3 digit numeric series

2006-03-12 Thread Shawn Corey

Robin Sheat wrote:

On Sunday 12 March 2006 18:22, Shawn Corey wrote:

Believe it or not, write the number as a string.
for ( '000' .. '100' ){
   print $_\n;
}
Note that if you have a string such as 000, you can treat it like a 
number:

my $a = '000';
$a++;
print $a\n;

This will print '001'.

To have it go to 4 digits, well, that's as easy as you might expect:
my $a = '999';
$a++;
print $a\n;

This will print '1000'.



This trick also works on letters:

#!/usr/bin/perl

use strict;
use warnings;

for ( 'a0' .. 'z9' ){
  print $_\n;
}

__END__

See `perldoc perlop` and search for Auto-increment and Auto-decrement


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Padded 3 digit numeric series

2006-03-12 Thread Shawn Corey

Harry Putnam wrote:

Ahh.  Nice, thanks.  I didn't recognize the
  `q[...]' usage but it appears to operate the same as
  
  %03d,ext, $number;


No, it would be the same as '%03d.ext' On the other hand, qq[%03d.ext] 
would be the same as %03d.ext


See `perldoc perlop` and search for Quote and Quote-like Operators

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Padded 3 digit numeric series

2006-03-12 Thread Shawn Corey

Harry Putnam wrote:

This has the right output but its not very obvious how one would use
this to increment a counter and files are being renamed.


As you would any other variable that contains a string.

  my $file = $_.ext;

or

  my $file = $_ . '.ext';

or

  my $file = sprintf( '%s.ext', $_ );

or even

  my $file = sprintf( q/%03d.ext/, $_ );

though this sort of defeats the purpose of auto-incrementing a string.

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: What is wrong with this file copy script

2006-03-12 Thread Shawn Corey

Harry Putnam wrote:

I'm already bald so don't have the luxury of pulling hair over this.

I don't understand the error ouput or maybe I could get somewhere with
this.   Pouring over perldoc File::Copy isn't helping either... I
think the error is before that but can't see what.

The end result of this script is supposed to be a directory named
./tmp with any copied files renamed into it.

The incoming files from ./dir1 ./dir2 are all files with numeric
names.  The total of them is 117

If I leave out the copy part it prints just what you'd expect so
somehow when inserting the copy funtion things change.

It fails on the first copy:

   hpdb cp'ing  ./dir1/2765 =  ./tmp/001
   Failed to copy ./dir1/2765 = ./tmp/001: No such file or directory
   at ./renum2.pl line 111


When File::Find goes looking for files, it chdir's to each directory its 
looking in. When it's in ./dir1, there is no ./dir1/tmp to copy files 
into, so you get an error. Change your calling sequence of find() to:


  find( { wanted = \wanted, no_chdir = 1, }, @searchdir);

See `perldoc File::Find` for details.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: script won't create text file on server

2006-03-12 Thread Shawn Corey

Elliot Holden wrote:
for some reason or another, my script won't create the text file that it 
is supposed to create on the server. For example, I'm taking a survey 
and calculating votes for a favorite song. The script IS calculating the 
votes so the text file is being created somewhere, but the text file is 
not showing up in the cgi directory where the script is located. If it 
is, I just can't see it. The purpose of the text file is to hold each 
vote. Are there any permissions or anything weird that has to be done. 
Godaddy is my hosting provider. This is a basic script that I followed 
out of a beginners book, so I know everything is correct in the script 
plus it IS working, I just can't see the text file that is holding the 
votes.


Elliot



Without seeing the script it is hard to give advise. Could you include 
the part of the script that creates the file path and name and the open 
statement?


Don't forget that CGI scripts are ran under the user who runs the 
server. It is possible that the file is ending up in this user's home 
directory. If you're not sure where this is, check with your server 
administrator.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: What is wrong with this file copy script

2006-03-12 Thread Shawn Corey

Harry Putnam wrote:

That formula did'nt do it either but it did show a different error
that throws some light on this.

Notice the first file is the directory name dir1
hpdb cp'ing  ./dir1 =  tmp/001

  Failed to copy ./dir1 =  
tmp/001: Is a directory at ./renum2.pl line 113


Thats why copy is failing.  


Is it normal for File:Find to list the directory name as the first
file found?


Yes. You should test everything to see if it's a file:

  if( -f $_ ){
# copy
  }

See `perldoc perlfunc` and search for -X FILEHANDLE

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: What is wrong with this file copy script

2006-03-12 Thread Shawn Corey

Harry Putnam wrote:

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

@directories = (./dir1, ./dir2);

for(@directories) {
  opendir(WRK_DIR,$_);


opendir(WRK_DIR,$_) or die cannot opendir $_: $!\n;


  chdir $_;


chdir $_ or die cannot chdir $_: $!\n;
# This fails for the second directory since it chdir to './dir2' when 
it's in './dir1' Try it from the command line:


  cd ./dir1
  cd ./dir2

Note the second one fails. TO get around this:

  use Cwd;
  my $cwd = cwd;
  chdir $_ or die cannot chdir $_: $!\n;
...
  chdir $cwd; # Change back at end of the loop.

  print hpdb thisdir=$_  \n;


  @fnames = grep { /\d/ } readdir(WRK_DIR);
  closedir(WRK_DIR);
  print $_ has  . @fnames .  files\n;
}

The output puzzles me:

  hpdb thisdir=./dir1  
  ./dir1 has 57 files
  -- 
  hpdb thisdir=./dir2  
  ./dir2 has 0 files


dir2 is not empty ... its a copy of dir1

Now if I comment out the `chdir' line:
I get the expected results.  (I don't understand why)

  hpdb thisdir=./dir1  
  ./dir1 has 57 files
  -- 
  hpdb thisdir=./dir2  
  ./dir2 has 57 files

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Padded 3 digit numeric series

2006-03-11 Thread Shawn Corey

Harry Putnam wrote:

Taking the chicken way out... but I can't think of the right tricky
search strings to uncover a tried and true way to output a 3 digit
padded numeric series.  In this case its for file names.  And needs to
roll over to 4 digit in the event there are enough files.

There is no problem of clobbering since files are being renamed as
they are moved to a new clean directory.  I just can't recall how to
make my incremented counter start at 000 and go:
001.ext
002.ext
003.ext
 etc.

Its just the numeric part I need a jump start on.




Believe it or not, write the number as a string.

#!/usr/bin/perl

use strict;
use warnings;

for ( '000' .. '100' ){
  print $_\n;
}

__END__




--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: i say literal; perl says metacharacter

2006-03-10 Thread Shawn Corey

Tom Phoenix wrote:

On 3/10/06, tom arnall [EMAIL PROTECTED] wrote:


is there any way to get perl to interpret the contents of $f as a literal?


I think you're looking for the quotemeta() function. Hope this helps!

--Tom Phoenix
Stonehenge Perl Training



You can also use the \Q meta-character:

  s/\Q$f\E$g/$f$h/;

See `perldoc perlop` for details.

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Does this script have the efficiency problems?

2006-03-09 Thread Shawn Corey

Chris Devers wrote:

On Thu, 9 Mar 2006, Practical Perl wrote:


Here is my script:

#!/usr/bin/perl
use strict;
use warnings;

my $date=`date +%y%m%d`;
chomp $date;


^^^

Not that this is your problem, but why on earth are you shelling out for 
the date? Perl can do this just fine, you know, and you don't even have 
to chomp() the result :-)


Try:

#!/usr/bin/perl

use strict;
use warnings;

use POSIX;

my @now = localtime;
print strftime( '%y%m%d', @now ), \n;

__END__

The function strftime(3) uses the same format conversion specifications 
as date(1). See `man strftime` for details.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: how to translate time string

2006-03-09 Thread Shawn Corey

Jeff Pang wrote:

Hello,list,

Maybe it's a simple problem,but I don't know how to do it.

I have a time string,for example:
Thu Mar  9 23:04:03 2006

How can  I get it translated to unix timestamp,for example:
1141916656

Thanks.

--
Jeff Pang
NetEase AntiSpam Team
http://corp.netease.com



POSIX has a function mktime that converts arrays returned by localtime 
back in seconds from the epoch. You would have to parse the date string 
into the appropriate array.


See `perldoc POSIX` and search for mktime
See `man mktime` and search for mktime

I have never used the function myself so its implementation is left as 
an exercise for the reader.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: pushing csv vaules into hash

2006-03-09 Thread Shawn Corey

Curt Shaffer wrote:

I am really stuck here. I need to split values from a csv value and push
them into an array, then perform a routine for all of them in a foreach
statement. In this example I am reading an email address, a username and a
password and needing to send each user listed in the csv a mail to the email
address with the message containing their username and password. I am
successful in reading the lines of the file and the ability to iterate
through them with once they are in the array, but then how do I get them
into variables to be used by the sub? Again in this example, I need to
create a variable ($to) from the first value, a username ($username) from
the second value and a password($password) from the third value. Those
variables will obviously be different for each iteration through the
foreach.


Parsing CSV is difficult since it uses a double escape mechanism. I 
suggest you go to CPAN and download a module to do the work for you.


http://search.cpan.org/search?m=moduleq=csvs=1n=100

I normally don't do work like this (I push it off onto junior 
programmers, it builds character ;) so implementation is once again left 
as an exercise for the reader.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Strange problem assigning values to strings

2006-03-09 Thread Shawn Corey

Bisbal, Prentice wrote:
I've got a strange problem. This perl code has been in use for a long time (6 - 12 mos, at least), and it just started behaving badly the other day. 

This code: 


foreach $num (@ids) {
$infile = $tmpdir/lp-$num.mol;
$outfile = $original_dir/lp-$num.$type;
print infile = $infile\n;
print outfile = $outfile\n;
if ($verbose) {
print Converting $infile (2D) to $outfile (2D).\n;
}
system $babel -imol $infile -o$type $outfile;
if ($verbose) {
print Removing temporary file $infile.\n;
}
unlink $infile;

Produces this output:

.molle = /tmp/lexchem2x.14745/lp-706840
.sdfile = /home/prentice/cadd/mins_lexchem2x_problem/lp-706840
/usr/local/bin/babel: cannot read input file!
.molle = /tmp/lexchem2x.14745/lp-706846
.sdfile = /home/prentice/cadd/mins_lexchem2x_problem/lp-706846

It should look like this:

infile = /tmp/lexchem2x.14745/lp-706840.mol
outfile = /home/prentice/cadd/mins_lexchem2x_problem/lp-706840.sd
/usr/local/bin/babel: cannot read input file!
infile = /tmp/lexchem2x.14745/lp-706846.mol
outfile = /home/prentice/cadd/mins_lexchem2x_problem/lp-706846.sd
/usr/local/bin/babel: cannot read input file!

Any idea what is going wrong here? 


Prentice




Just a WAG but one of your @ids is 706846\r


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Strange problem assigning values to strings

2006-03-09 Thread Shawn Corey

Bisbal, Prentice wrote:

I think you're on to something. This is what the debugger shows:

 DB17 x [EMAIL PROTECTED]
0  ARRAY(0x90c420c)
   0  706840\cM
   1  706846\cM
   2  715596\cM
   3  715620\cM
   4  722292\cM
   5  722300\cM
   6  722327\cM
   7  722330\cM
   8  722340\cM
   9  722468\cM
   10  722894\cM
   11  723594\cM
   12  723618\cM
   13  723620\cM
   14  723660\cM
   15  723668\cM
   16  723674\cM
   17  723691\cM
   18  723695\cM
   19  723962\cM
   20  724072\cM
   21  724104\cM
   22  724185\cM
   23  724189\cM

Ctrl-M is a carriage return, How can I eliminate a carriage return? Will 
chomp work, or is that only for newlines?


Prentice


I think chomp is only for newlines (ASCII 0x0a). chop will cut off the 
last character. But to be safe use:


  $num =~ s/\cM//g;


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

This statement is true but unprovable.
  Kurt Godel

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: question on pattern matching

2006-03-07 Thread Shawn Corey

Gavin Bowlby wrote:
So 


(\.)?

differs from

(\.?)

in that there is no match in the first case, but there is a match in the
second case?

I'm still confused as to why the placement of the ? operator inside or
outside the parentheses makes a difference.

I thought the parentheses were only there to bind the result to a $N
variable, not to change the operations of the pattern matching itself.
  

Parentheses are also used for grouping, as in:

 /(foo|bar)/

With '(\.)?' the group is optional; with '(\.?)' the string inside the 
group is optional, the group is not.


--

Just my 0.0002 million dollars worth,
  --- Shawn

Probability is now one. Any problems that are left are your own.
  SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

This statement is unprovable. -- Kurt Godel


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: import modules at begin block

2006-01-23 Thread Shawn Corey

Peter Scott wrote:

Maybe I'm missing something, but the poster appears to be asking how to
achieve the common and useful pattern of plugins, where you control
dynamic behavior by deciding what modules are in a particular directory. 
Of course there's a lot more scaffolding than the poster alluded to, but

at some point you do have to load all the modules in a directory.  My
current favorite way is to eval each file one at a time and extract
package directives to push class names onto an array. 


Ken: that won't work.  You need BEGIN blocks, glob(), and a require
followed by a $class-import inside the loop. 



Every now and again someone gets the bright idea to load modules 
dynamically. Usually they do this to save time. The correct way to do 
this is to rewrite the modules for AutoLoader. Then you just 'use' 
everything. See `perldoc AutoLoader` for details.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: File Parsing Question

2006-01-22 Thread Shawn Corey

William Black wrote:

Hello,

I'm trying to figure out how to read multiple lines from a file at once for
parsing.  For example,, If the file contained the following:

input file

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8

I want to read in lines 1-4 for processing then during the next iteration
read lines 5-8.  Could someone give me a could starting place?


I know of no other way than the hard way.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

while( ! eof DATA ){
  my @lines = ();
  for my $i ( 1 .. 4 ){
my $line = DATA;
push @lines, $line;
  }

  # process @lines
  print Dumper [EMAIL PROTECTED];

}

__END__
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: somthing wrong with my codes???

2006-01-21 Thread Shawn Corey

chen li wrote:

#!/usr/bin/perl
use warnings;
use strict;

 my $string=password=xyz verbose=9 score=0;
 my @keys=();
 my @values=();
 while ($string=~/(\w+)=(\w+)/g){

  @keys=push(@keys, $1);


  push @keys, $1;


  print $1, \n;
  @values=push(@values,$2);


  push @values, $2;


  print $2, \n;
 }
print \nThese are the keys:,@keys;

print \nThese are the values:,@values,\n;
exit;


__END__

See `perldoc -f push` for details, especially the part about the 
returned value.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: removing line feeds

2006-01-21 Thread Shawn Corey

Bowen, Bruce wrote:

I know how to get rid of the carriage returns using s/\n//g,

 but haven't had any luck in finding the way to get rid
 of the line feeds following the |fs.

Sorry, \n means a line feed. Try:

  s/\n//g; # Remove line feeds
  s/\r//g; # Remove carriage returns

See:
perldoc perlre
perldoc perlretut
perldoc perlrequick


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: negative match

2006-01-20 Thread Shawn Corey

Adriano Allora wrote:

hi to all,

I cannot use a negative match, and I cannot understand why: someone may 
help me?


I've got this four rows (for instance):

arabaADJ arabo
araboADJ arabo
araboNOM arabo
aranoVER:presarare

and, with this regular expression, I would extract only the fourth one:

my $form1 = qw(ara\w+);
my $pos1 = qw([A-Z]+);
my $lemma1 = qw(?!arabo);
my $pattern = ^(?:$form1)[^A-Z]*($pos1)[^A-Z]*($lemma1)\n;

but it doesn't work (the script extracts all the lines).



From `perldoc perlre`:

   (?!pattern)
 A zero-width negative look-ahead assertion.

This means $lemma1 will match a string of zero length, which is ALWAYS 
before the newline.


Your problem is that you are trying to do too much with a single 
pattern. You should avoid this because it makes understanding, and 
therefore maintenance, difficult. Try:


  if( /^ara/  ! /arabo\n$/  /([A-Z]+)/ ){
print \$1 = $1\n;
print yes: $_;
  }else{
print no : $_;
  }


ANOTHER QUESTION: is there a module to merge different arrays and 
extract equal values or I have to use a foreach statement?


No, Try:

  my %hash = map { $_ = 1 } @array1;
  for ( @array2 ){
push @both, $_ if $hash{$_};
  }


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: filehandle question

2006-01-17 Thread Shawn Corey

radhika wrote:

Hi,

Can someone tell me what is going on in this peice of code?
Especially, line 409.

--code start--
405my $fh;
406my $txtfile = $file-fileName();
407open $fh, $txtfile;


open $fh, $txtfile or die cannot open $txtfile: $!\n;


408my $plain_text = '';
409$plain_text .= $_ foreach ($fh);
   close $fh;
--code end--

I keep getting this error:

readline() on closed filehandle $fh at
/home/ars/sys/libperl/site/ARS/REPORTS/AggregateFills.pm line 409.

Thanks!
--Rs




--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: about the var's scope

2006-01-16 Thread Shawn Corey

Jeff Pang wrote:

I think the only difference between the two is Stat's code do the things of 
sharing vars across modules really.
Under mod_perl,the situation is very different from common CGI environment,and 
the vars sharing sometimes is useful and needed.
I hope I'm correct.If not,the criticism are welcome.


The OP was asking about understanding the code, not what are the best 
practices. First of all, I would never call an object by a single 
letter. Something like $CGI_Obj would be better. And being a global, it 
starts with a capital.


Yes, I would be more inclined to pass the object to the subroutines than 
use it as a global. I would use Exporter only to export subroutines, not 
variables because, as discussed, it is difficult to understand what is 
happening.


I don't use mod_perl but my understanding it that it doesn't, or didn't, 
reset the globals to the default state (which is undef). Of course, 
setting all your variables to a known state before using them is 
consider good practice; so you should never encounter this problem ;)



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: assigning list to hash entry

2006-01-16 Thread Shawn Corey

Xavier Noria wrote:
In Perl data estructures can only store scalar values. That's why  
references are used to emulate nested structures:


$hash{$key}[0] = [EMAIL PROTECTED]; # note that @s are arrays, not lists
$hash{$key}[1] = $string;
$hash{$key}[2] = \%hash;

There are some pages in the documentation about nested estructures,  
have a glance at perldsc for instance.


An alternative would be:
  $hash{$key}[0] = [ @array ];
and
  $hash{$key}[2] = { %hash };

Here you are making a copy of the the array and hash. In the above, if 
you change @array or %hash, then the contents of $hash{$key}[0] and 
$hash{$key}[2] also change. It depends in what you want; sometimes you 
want it one way, sometimes the other.


Also you could have written:
  $hash{$key}[1] = \$string;
So that when $string changes, $hash{$key}[1] also changes.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: interpolation

2006-01-16 Thread Shawn Corey

John Doe wrote:

The Ghost am Montag, 16. Januar 2006 06.34:


I am storing text stings in a database.  when I have the string:

'some perl $variable'

which would print as:

some perl $variable

how can I force interpolation of '$variable'?

one idea I thought of was:
#!/usr/bin/perl
my $var='variable';
$string='some $var';
$string=~s/\$(\w+)/${$1}/gi;
print $string\n;

But it doesn't work.  I want it to print some variable.



One way is to change the regex a bit:

#!/usr/bin/perl
use strict;
use warnings;

my $var='variable';
my $other_var='another';
my ($string1, $string2, $string3)=map 'some $var $other_var', 1..3; 


# test1, test2, final version:
#
$string1=~s/(\$\w+)/$1/g;
$string2=~s/(\$\w+)/$1/ge;
$string3=~s/(\$\w+)/$1/gee;

print join \n, $string1, $string2, $string3;


greetings
joe



Usually it is considered a bad idea to interpolate external strings. You 
could have your users printing any variable. Consider using sprintf 
instead (see `perldoc -f sprintf`).


my $format = 'some perl %s';
my $string = sprintf $format, $variable;
print $string\n;


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: How to take a reference in line

2006-01-16 Thread Shawn Corey

Bill Gradwohl wrote:

my $arrayPointer;

# This works:
@{$arrayPointer}=qw(Money preserver sunscreen);
check_required_items(Mr. Howell, $arrayPointer);

# These don't work:
check_required_items(Mr. Howell, @{$arrayPointer}=qw(Money preserver 
sunscreen));
check_required_items(Mr. Howell, qw(Money preserver sunscreen));


How do I tell Perl to give me a reference to an array in the last 2
statements? There's got to be a way to pass a reference without having
to explicitly name a variable. Right?


Try:
  check_required_items(Mr. Howell, $arrayPointer=[qw(Money preserver 
sunscreen)] );

  check_required_items(Mr. Howell, [qw(Money preserver sunscreen)] );


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Array of hashes

2006-01-16 Thread Shawn Corey

[EMAIL PROTECTED] wrote:


Hi All

Can anyone tell me whether there is any way for declaring an array of
hashes similar to creating array of structure variables in C
programming?


There is a module, Class::Struct, that might be what you want. See 
`perldoc Class:Struct`.


However, I would simply build the array of hashes as I go:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my @ArrayOfHashes = ();

for my $count ( 1 .. 10 ){

  my %hash = ();
  for my $key ( 'a' .. 'z' ){
my $value = rand;
$hash{$key} = $value;
  }

  push @ArrayOfHashes, { %hash };
}

print Dumper [EMAIL PROTECTED];

__END__


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: about the var's scope

2006-01-15 Thread Shawn Corey

Jeff Pang wrote:

Hello,lists,

Seeing these code below please.I can't know why the var defined in the main 
script can been accessed in the modules that used by the main script?thanks.


From `perldoc vars`:

While the vars pragma cannot duplicate the effect of package lexicals 
(total transparency outside of the package), it can act as an acceptable 
substitute by pre-declaring global symbols, ensuring their availability 
to the later-loaded routines.


This means any variable declared by vars can be accessed outside of the 
file it is declared in.


The second part of the understanding comes from Exporter. When it 
exports a thingy, it uses a typeglob to make the thingy in the package 
the same as in the 'use'ing module. In other words, for your My::HTML 
module, it does this:


  $main::q = \*My::HTML::q;


For more details, see:

  perldoc vars
  perldoc -f our
  perldoc perlfunc (and search for 'our')

  perldoc Exporter
  perldoc perlop (and search for 'typeglob')
  perldoc perlsub (and search for 'typeglob')


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: assigning list to hash entry

2006-01-15 Thread Shawn Corey

Anders Stegmann wrote:
Hi! 
 
how do I assign a list to a hash entry like $hash{$key}[0]. 
 
I mean, something like this: 
 
$hash{$key}[0] = @list; 
 
must work. 
 
Anders. 





Close. Try:

use Data::Dumper;
$hash{$key} = [ @list ];
print Dumper( \%hash );


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: contest software

2006-01-15 Thread Shawn Corey

Mike Blezien wrote:

Hello,

we're looking for a good contest software written perl, for creating 
various types of contests. before we embark on building from the ground 
up, wanted too see if there any out there that may meet our needs.


any feedback would be appreciated.

TIA,


Please write in English. You are not some newbie asking to solve some 
problem in a language you haven't mastered. You are professionals asking 
for help from other professionals. Hire someone to translate your words.


This is a beginners group. Do you really think you're going to find 
something worthwhile here? Well, miracles happen, but don't count on 
them; take your message to a more advance group.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: about the var's scope

2006-01-15 Thread Shawn Corey

John Doe wrote:

[reordered to bottom style posting]
Jeff Pang am Montag, 16. Januar 2006 01.59:


Thanks for Shawn.The main script can see the global var $q coming from
module,since the main script import this symbol via 'use My::HTML
qw($q)'.But the modules have no any importing behavior,why they can see the
global var $q coming from main script?I'm really confused for that.



Ok, it would be interesting to look deeper into the mess of different 
variables all named with the same name $q, exported across the modules, 
overwritten by several imports...


What do you want to achieve with your code? It looks really strange (hm, at 
least to me).


joe



All the variables $q in the packages have been shunted aside into the 
deep, dark bit bucket of oblivion.


As I said before:

  $main::q = \*My::HTML::q;
  $main::q = \*My::Doc::q;

$My::HTML::q and $My::Doc::q no longer exist; they are aliases to 
$main::q. In the modules, $q no longer exists; it is an alias for 
$main::q. Whenever you say $q in the modules, you really mean $main::q. 
The modules do not import anything; they export any changes to $main::q; 
via the phrase '$q'.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: the 'tail' problem

2006-01-14 Thread Shawn Corey

Jeff Pang wrote:

hi,lists,

I have a log file which is a symbol link to the real logfile,shown as following:

$ll mssvr.log
lrwxrwxrwx1 cmail root   40 Jan 14 00:00 mssvr.log - 
/home/cmail/logs/mssvr.log.2006-01-14

I have to access this file in perl script with unix 'tail -f' command.Part of 
the code is below:

open (TAIL,tail -f $log|) or die can't open pipe:$!;
while(TAIL)
{
do something...
}

This script is a daemon script which run permanently.There is no problem when 
in the same day.But when the date changed,the symbol link file will point to 
another real logfile automatically (which decided by other application 
program),such as:

lrwxrwxrwx1 cmail root   40 Jan 14 00:00 mssvr.log - 
/home/cmail/logs/mssvr.log.2006-01-15

As you see,it's '2006-01-15' now, not '2006-01-14' as before.So the 'tail -f 
$log' become no use for the new symbol link file,and I can't get any input from 
the new logfile in the script.

How can I adjust this problem?Thanks a lot.


Jeff



You could try File::Tail from CPAN.
http://search.cpan.org/~mgrabnar/File-Tail-0.99.3/
http://search.cpan.org/~mgrabnar/File-Tail-0.99.3/Tail.pm
I haven't used it myself so I can't tell if it will solve your problem. 
If it doesn't, you'll have to roll your own. Look up the following:


perldoc -f lstat
perldoc -f readlink
perldoc -f tell
perldoc -f seek

Basically, you would have to keep track of where you are in the file and 
when the date changes, open the new file.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Matching the first string

2006-01-13 Thread Shawn Corey

John Doe wrote:

[EMAIL PROTECTED] am Freitag, 13. Januar 2006 18.28:
[...]


i`ve written a script whose purpose is to put files in different
directories by its first later, the problem is that every file begins
with different chars for example 01 - Eminem Encore.mp3
my question is how can i get to the first latter in the name (in this
case it was E), i need just the expression that does it.


/([a-zA-Z])/;



I think your version does the same as mine,
/^[^a-zA-Z]*([a-zA-Z])/
which looks somehow brain dead...


/([[:alpha:]])/;
my $first_letter = $1;

See `perldoc perlre` and search for 'alpha'. Sorry does not work with 
UNICODE characters, just the lower 256.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: What does this line of code say?

2006-01-11 Thread Shawn Corey

Bill Gradwohl wrote:

I'll study that one after I TOTALLY understand my original problem.
Thank you for another eye opener  head scratcher.



To see what's inside a complex data structure, use Data::Dumper. In this 
case, add the lines:


  use Data::Dumper;
  print Dumper \%children;

See `perldoc Data::Dumper` for details.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Byte array

2006-01-10 Thread Shawn Corey

[EMAIL PROTECTED] wrote:

I'm new to Perl and am trying to set a variable length byte array that is
passed to a socket as a string for output. I have the following which works,
but the commented out code doesn't.  What am I doing wrong?  Thanks.
use IO::Socket;
use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
my $sock = new IO::Socket::INET( PeerAddr = '10.10.2.141', PeerPort =
'5', Proto = 'udp' );
die no socket\n unless $sock;
$totalNumPkts = 1;
$pktSize = 512;
$dataVal = 'U';
$iPkt = 1;
for ( $i = 1; $i  $pktSize; $i++ )
{
$iPkt += 1;
}


This loop can be replaced with: $iPkt = 513;
Or do you want a string of 512 ones? $iPkt = '1' x 512;
You should print out $iPkt to make sure it contains what you think it 
does: printf %5d %s\n, length($iPkt), $iPkt;



$startTime = Time::HiRes::time;
for ( $i = 1; $i = $totalNumPkts; $i++ )
{
print sending msg ..;
$sock-print( Hello\n );
#$sock-print( $iPkt );
}
$endTime = Time::HiRes::time;
$totalTime = $endTime - $startTime;
printf(  st %f end %f total time=%f time/pkt=%f\n, $startTime, $endTime,
$totalTime, $totalTime / 
$totalNumPkts );

printf(done\n);
close( $sock );




--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Need some help and direction

2006-01-08 Thread Shawn Corey

Daniel Gladstone wrote:
I thought this would be easy but I can not get it to work - can someone 
please help me:


Problem: I have a file of 7.5 million records that are pipe delimted, 
the first field is a record
number. I want to search for around 10 records with a specific record 
number and if they
meet that condition, output them to a secondary output. And if it does 
not meet the record

number criteria, output to the primary output.

Code so far(Please don't laugh - I am a newbie)

#!/usr/bin/perl -w
use strict;
# pullbad filename fieldtocount
die usage: count filename count fldnum \n unless (@ARGV == 2);
my ($filename, $cntfldnum) = @ARGV;
$cntfldnum--; # zero-base fldnum
my $records = 0; # count records processed

open(IN, $filename) or die could not open $filename $!\n;
my %count = (); # hash the count key and value here
while (IN) {
 $records++;
 my @rec=split(/\|/,$_);
 #$count{$rec[$cntfldnum]}++;
 if ($rec[$cntfldnum] =~ m/\D/g) {
print STDERR $rec[$cntfldnum] .  -  . $rec[0] .  record # =  . 
$records . \n;

 }


Your code doesn't seem to match the problem you stated. What does 
$cntfldnum contain? If you are searching, as you stated, for a record 
number then the match pattern should be for column zero: $rec[0] =~ 
/$pattern/ Could you please clarify your intent?



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: new for reading file containing multiple records

2006-01-08 Thread Shawn Corey

chen li wrote:


You are 50% right. This method is not correct for the
first record(which actually contains ' only) but it
is correct for the last record(and others in between).



I want to edit the file first and try to delete the
first  in this big file. I browse Programming Perl
and Perl Cookbook there is not such  example: just
delete the first charater in a file. But they have
examples to delete the last line from a file. It seems
odd to me. 


First, I'd recommend against changing a large file. Unless your program 
is the only user of the file, you would have to change all the other 
programs. And in this case, you would be unable to distinguish one 
record from another.


There are three ways to distinguish records in a file: by record 
separators, by beginning-of-record tokens, and by end-of-record tokens. 
Your file may use one, two or all three methods. When writing code, your 
preference should be (in order) record separator, end-of-record token, 
and finally beginning-of-record token.


In Perl, the variable $/ is used to distinguish the end-of-record token; 
even though it is called the INPUT_RECORD_SEPARATOR. Its name is 
misleading. If it was a true record separator, your code would never 
have to process the record separator; it would be discarded at a lower 
level.


The records in your file are distinguished only by a beginning-of-record 
token, specifically a greater-than sign at the beginning of a record. 
You can process the file in two ways: treat the beginning-of record 
token as an end-of-record token, or read ahead in the file and process 
the record only after reading the beginning of the next record. Both 
have the advantages and disadvantages.


If you want to treat the beginning-of-record token as an end-of-record 
one, your records are going to have some anomalies. The first record is 
going to have a beginning-of-record token attached to it. Your last 
record is not going to have an end-of-record token. For your case, it 
would look something like this:


my $beginning_token = '';
my $end_token = \n$beginning_token;
$/ = $end_token;
my $first = 1;
while( FH ){
  if( $first ){
s/^\Q$beginning_token//;
$first = 0;
  }
  s/\Q$end_token\E$//;
  process_record( $_ );
}

If you want to use only the beginning-of-record token, you will have to 
do at least a partial read ahead. This means you have to store the read 
ahead and the last record will be processed outside the read loop. For 
you case:


my $beginning_token = '';
my $record = '';
while( FH ){
  if( /^\Q$beginning_token/ ){
if( $record =~ /^\Q$beginning_token/ ){
  process_record( $record );
}
$record = '';
  }
  $record .= $_;
}
if( $record =~ /^\Q$beginning_token/ ){
  process_record( $record );
}



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: executing external binaries

2006-01-07 Thread Shawn Corey

Saurabh Singhvi wrote:

hi people

i have a script that executes external binaries using the system command.
now the problem is this:

the external binary is HUGE in terms of ram usage so i need a way to keep it
loaded in the memory
so that i can keep passing the next parameters, instead of loading it each
time.

kindly guide me about this

thanks
Saurabh



If you're running UNIX you can set the binary's sticky bit. See `man 
chmod` and `man 2 chmod`. The sticky bit tells UNIX to leave the program 
in RAM for a little while in case it is called again very soon.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: new for reading file containing multiple records

2006-01-06 Thread Shawn Corey

chen li wrote:

Each record starts with . I want to read each
record once at a time.I hear about a special variable
call $/ might do the job but not sure how to use it. I
wonder if anyone could help me out.


See `perldoc perlvar` and search for INPUT_RECORD_SEPARATOR.

Here is a simple script which might do:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

$/ = ;
while( DATA ){
  print Dumper \$_;
}

__END__
gi|618748|dbj|D21618.1| MUS74F01 mouse embryonal carcinoma cell line 
F9 Mus mus culus cDNA clone 74F01, mRNA sequence

GCTGCCTCGACGATCTTCGCTTGCNTCCTCGCTCGCTGTCCCGTTGTCCTAGCCCGCCGCCGCCCGCTGAGCTTGTCTTTACCCTGCTTGCAGACATGGCTGACATCAAGAACAAGAATATTTCTTTCGTNANCC
GGTGTNATGGCGCTCGTCCGCAATGAGCGGCATGGGCCGCTATTGACAGCAAGAG
gi|618749|dbj|D21619.1| MUS74F09 mouse embryonal carcinoma cell line 
F9 Mus mus culus cDNA clone 74F09, mRNA sequence

GGCGNNNTGGCCTCGGGCGGCTGGACGTGCCCAGCGCCCGATTAACAAGATACATTTAATTGCTGTGTTTAACCAAATGTTTGAAGGCTGTGGGACTGAAATCATATGATCTCCTGCTGTTCACATTGTTC
ATTAA


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: pack an array

2006-01-02 Thread Shawn Corey

Gerard Robin wrote:

Hello,
I guess that one can write in more perlish fashion that I did: the part 
between the  of this script to pack the array @array.


Please, can someone give me some hint ?

#!/usr/bin/perl
# pack_array.pl

use strict;
use warnings;

my $string = [EMAIL PROTECTED] n??e#w [?! \$ \% y]e{?]a##r? 
2\*0\$0'\6\# ! \^;

my @array = split / /, $string;

foreach (@array) {

 s/[EMAIL PROTECTED]^'\]\[\*{]//g;
}

my @pack;
my $j = 0;

foreach my $i (0..$#array) {

 if ($array[$i] eq '') {

   $i++;

 } else {

   $pack[$j] = $array[$i];

   $j++;

 }
}
#

print @pack\n;

__END__

tia



Is this what you mean?

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my $string = [EMAIL PROTECTED] n??e#w [?! \$ \% y]e{?]a##r? 
2\*0\$0'\6\# ! \^;

$string =~ s/[EMAIL PROTECTED]^'\]\[\*{\s]+/ /g;
print $string\n;

my @array = split /\s+/, $string;
print @array\n;

__END__


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Running Other Programs from Perl (WAS: Am a newbie ....)

2005-12-20 Thread Shawn Corey

Brahadambal S wrote:

Hi,

Could anyone tell me how to execute a .bat or .exe file through Perl? i.e, the 
perl code should invoke the executable. Thanks so much for your help(in 
advance).



Open a terminal and type:
perldoc -f system
perldoc perlop (and search for 'qx')
perldoc perlopentut


--

Just my 0.0002 million dollars worth,
   --- Shawn

* Perl tutorials at http://perlmonks.org/?node=Tutorials

* Always write your code as though you aren't going to see it
* for another 25 years and then one day your boss comes up to you
* and says, I want these changes and I want them yesterday!

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: use constant

2005-12-20 Thread Shawn Corey

David Gilden wrote:

I looked for documentation on 'use constant'  but it has eluded it me.


perldoc constant


--

Just my 0.0002 million dollars worth,
   --- Shawn

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

* Always write your code as though you aren't going to see it
* for another 25 years and then one day your boss comes up to you
* and says, I want these changes and I want them yesterday!

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: syntax of a perl program?

2005-12-20 Thread Shawn Corey

anand kumar wrote:

Hi all
 Can anyone let me know some functions or some tutorial on how to 
check the syntax of a perl program.


perldoc -c your_script

See:
perldoc perlrun (and search for '-c')


--

Just my 0.0002 million dollars worth,
   --- Shawn

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/

* Always write your code as though you aren't going to see it
* for another 25 years and then one day your boss comes up to you
* and says, I want these changes and I want them yesterday!

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Constant Hash problem

2005-12-19 Thread Shawn Corey

John W. Krahn wrote:

Shawn Corey wrote:

for my $key ( sort keys %{ { STOPWORDS } } ){
 my $value = ${ { STOPWORDS } }{$key};



In both lines you are copying the entire list to an anonymous hash.  If you
want efficient code (and less punctuation) you should just use a hash.


Efficiency. There's that word again. If you truly want efficient code 
you won't create subroutines that return lists. They would return 
references to the lists or store them in global arrays.



--

Just my 0.0002 million dollars worth,
   --- Shawn

* Perl tutorials at http://perlmonks.org/?node=Tutorials

* Always write your code as though you aren't going to see it
* for another 25 years and then one day your boss comes up to you
* and says, I want these changes and I want them yesterday!

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Constant Hash problem

2005-12-17 Thread Shawn Corey

John W. Krahn wrote:

You can't because perl implements constants using subroutines and subroutines
can only return a list.


Perl subroutines return only lists but it converts them to hashes 
automatically:


#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

sub list_to_hash {
  return qw( a 1 b 2 c 3 );
}

my %hash = list_to_hash();

print Dumper( \%hash );

__END__


The thing about constant is that does not create a true constant; it 
creates a reference to an anonymous subroutine. You have to learn to use 
it as such:


#!/usr/bin/perl

use strict;
use warnings;

use constant STOPWORDS = map { $_, 1 } qw(a about above across adj after);

for my $key ( sort keys %{ { STOPWORDS } } ){
  my $value = ${ { STOPWORDS } }{$key};
  print $key = $value\n;
}

__END__

Interpretation:

%{ { STOPWORDS } } means create an anonymous hash from the list returned 
by STOPWORDS and then dereference it.


${ { STOPWORDS } }{$key} means create an anonymous hash from the list 
returned by STOPWORDS, dereference it, and get the value for $key.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: A question about modules

2005-12-17 Thread Shawn Corey

Robert wrote:

I simply use:

my $dbh = DBConn::db1();

It does the right connection (i.e. subroutine) from the DBConn package and I 
didn't use Exporter. I should also mention that DBConn is in the same folder 
and the calling script so maybe that makes a difference.


No, it doesn't. You can mix packages in any manner you like throughout 
your modules. Whether you should ...




I am probably going to go back and do a proper module of it so I can get in 
the habit of doing so.


If you want to make a proper module out of it, separate it into three, 
one for each connection. Then add (to each) a close connection 
subroutine, a commit, and a rollback. Change the names so that they are 
more descriptive of the data.


Always write your code as though you won't see it for 25 years and then 
have to change it yesterday.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Time::Local

2005-12-15 Thread Shawn Corey

richard lavoie wrote:
Hi dear list, 
 
I'm trying to write a little script for calculation with time like adding 
a few minutes to a certain time. 
I'm getting this message: 
Time::Local version 1134653954 required--this is only version 1.1 
at /usr/lib/perl5/5.8.6/Exporter/Heavy.pm line 121. 
BEGIN failed--compilation aborted at time.pl line 6. 
 
This is what I tried: 
 
#!/usr/bin/perl -w 
 
use lib /WHATEVER/Time-Local-1.11/lib; 
use Time::Local 


use Time::Local;
#--^ (look here)


# Otherwise Perl tries to load the results
# of the next statement as a subroutine

 
my $mytime = time; 
$mytime = 1; 
print $mytime\n; 
my @time = localtime($mytime); 
$zeit=$time[0]:$time[1]:$time[2]:$time[3]:$time[4]:$time[5]; 
print $zeit \n; 
my $timestamp = timelocal(1,2,3,1,1,2); 
print $timestamp\n; 
 
Thanx in advance 
R. 
 
 
 
 



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Equal length numbers

2005-12-15 Thread Shawn Corey

Andrej Kastrin wrote:

Hi all,

Suppose that we have numbers 1 to 1000 and we want all numbers be equal 
length; e.g.:

0001
0002
0003
...
..
1000

Any idea on how to fix this problem?

Best, Andrej




# perldoc -f sprintf

for ( 1 .. 1000 ){
  printf %04d\n, $_;
}


# version 2
#!/usr/bin/perl

use strict;
use warnings;

use POSIX;

my $max = shift @ARGV;
my $len = 1;
for ( my $n = 1; $n = $max; $n *= 10 ){
  $len ++;
}
$len --;

for ( 1 .. $max ){
  printf %0*d\n, $len, $_;
}

__END__


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: split regex

2005-12-15 Thread Shawn Corey

Umesh T G wrote:

I tried like this,   where $line='*Options=-ahello -mt -ml3 -idir1\dir2
-k -p -idir3\dir4 -m'*



This line won't compile. Which of the following is it?

$line='Options=-ahello -mt -ml3 -idir1\dir2 -k -p -idir3\dir4 -m';

$line='*Options=-ahello -mt -ml3 -idir1\dir2 -k -p -idir3\dir4 -m*';

Please test your code before posting.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: split regex

2005-12-15 Thread Shawn Corey

Umesh T G wrote:

Hi Joe,

just to correct my prevoius one,  my $line does not have * in the begining,
that was a type.  the $line value is like this

*Options=-ahello -mt -ml3 -idir1\dir2-k -p -idir3\dir4 -m*



my grep return the values correct to my array and the values in array will
be like this obviously:

*Options=-ahello -mt -ml3 *
*dir1\dir2-k -p *
*dir3\dir4 -m*
**
**
But, what I'm interested in getting the output values are:
*dir1\dir2*
*dir3\dir4*

I do not know how to get them..can u suggest pls.?


thanks
Umesh


#!/usr/bin/perl

use strict;
use warnings;

my $line='Options=-ahello -mt -ml3 -idir1\dir2 -k -p -idir3\dir4 -m';

for ( split /\s+/, $line ){
  if( /^-i(.*)/ ){
print $1\n;
  }
}

__END__



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: extracting substrings from string using regexp

2005-12-12 Thread Shawn Corey

Ing. Branislav Gerzo wrote:

you should learn regexpes, they are very powerful.
perldoc perlre


See also:
  perldoc perlrequick Perl regular expressions quick start
  perldoc perlretut   Perl regular expressions tutorial


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: indexing... in some way

2005-12-11 Thread Shawn Corey

Adriano Allora wrote:

`sort tagged_files/* | uniq  word+tag.txt`;


???

All files in tagged_files/* are unique. This looks like a lot of make 
work. Try File::Find instead. See `perldoc File::Find`.



open(IDX, word+tag.txt);
while(IDX)
{
next if /^\W.+/;
open(TMP, indexes/$_.txt);
$where = `grep -L '$_' tagged_files/*`;


This says you are looking for the file _NOT_ in the files' content. 
Perhaps you want '-l' instead? See `man grep`.



print TMP $where;
close(TMP);
}

someone would tell me why the line with grep does not work?
Is this the fastest way?


Considering the amount of work this does outside of Perl, no. A shell 
script would be faster. (But, of course, anything written in Perl is 
automatically better than everything else ;)



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: How to promote the efficiency

2005-12-08 Thread Shawn Corey

Jennifer Garner wrote:

hi,lists,

I have a file which is so large,which looking as:

61.156.49.18:28360
61.183.148.130:27433
222.90.207.251:25700
202.117.64.161:25054
218.58.59.73:24866
221.233.24.9:22507
222.187.124.4:21016
...

and more than 4500 lines.

the part after : is no use for me,I only need the IP.

for each IP,such as '218.58.59.73', I want to get this result:

218.58.59.  xxx yyy xxx+yyy

I want to know how many IP are in the range of '218.58.59.1' to '
218.58.59.127',this is 'xxx';
and how many IP are in the range of '218.58.59.128' to '218.58.59.254',this
is 'yyy'.

I write this code:
open (FILE,$file) or die $!;
while(FILE)
{
next if /unknown/o;
next if /^192\.168\./o;
chomp;
my ($ip,$num) = split/:/,$_;
if ($ip = ~  /^(\d+\.\d+\.\d+\.)(\d+)/o){
my ($net,$bit) = ($1,$2);
$total{$net}{low}{$bit} = 1 if $bit  128;
$total{$net}{high}{$bit} = 1 if $bit =128 and $bit 
255;
$total{$net}{total}{$bit} = 1;


# Accumulate the totals directly
if( $bit  128 ){
  $total{$net}{low} ++;
}else{
  $total{$net}{high} ++;
}
$total{$net}{total} ++;


}
}
close FILE;

foreach (sort { scalar keys %{$total{$b}{total}} = scalar keys
%{$total{$a}{total}} } keys %total)
{
print RESULT $_,\t,scalar keys %{$total{$_}{low}},\t,
  scalar keys %{$total{$_}{high}},\t,scalar keys
%{$total{$_}{total}},\n;
}



OK, we're going to use a technique called the Schwartzian 
transformation, named after our good friend Randal L. Schwartz, who 
invented it.


foreach (
  map { $_-[0] }
  sort { $b-[1] = $a-[1] }
  map { [ $_, $total{$_}{total} ] }
  keys %total
){
  print RESULT 
$_\t$total{$_}{low}\t$total{$_}{high}\t$total{$_}{total}\n;

}


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: chop/chomp/?

2005-12-08 Thread Shawn Corey

Frank Bax wrote:
What's the correct way to trim trailing newlines from a text file that 
might be either DOS or UNIX format for newlines? The docs (and my 
experience) is that chomp only works properly if the text file is native 
to the current operating system?  I'm running on *bsd system.





The correct way is to use chomp. In OSes like MS DOS, Perl automatically 
converts text files to UNIX format, so things like chomp work correctly.


See:
perldoc -f binmode

Note that since Perl's native OS is UNIX, there is no difference between 
a text file and a binary one. But you should include binmode for all 
binary files in case your code gets transferred to another OS where this 
is important.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: The Difference Between my Globals and our Globals (WAS: Parameterizing a module)

2005-12-08 Thread Shawn Corey

[EMAIL PROTECTED] wrote:

I see. Thanks Shawn. Since we are at it, would you mind explaining a little bit
about the significance of our keyword. I have never understood it properly.
Most books that I referred to say that it's a lexically-scoped global
variable. What does that mean? I understand global variables to be the ones
which are accessible to all perl program units (modules, packages or scripts).
But then, what is so lexically-scoped about it? What do the perl compiler and
opcode interpreter do when encounter a variable name prefixed by our? 


Below are three files, main, foo.pm, and bar.pm. These show the way 'my' 
and 'our' behave.


A 'my' global variable is scoped only to the file it is in. It hides any 
'our' variable (of the same name); you can only access the 'my' 
variable. 'our' variables are global globals; they are the same and 
accessible across files.


Below, you will note that the sub super_bar uses 'our' (in a block) to 
override the 'my' definition of $Self to access the 'our' one. With 
practice, you too can create code that is a nightmare for your maintainers.



#!/usr/bin/perl

use strict;
use warnings;

our $Self = __FILE__;

use foo;
use bar;

print main: $Self\n;
foo();
bar();
super_bar();

__END__


# foo.pm

our $Self = __FILE__;
print foo: $Self\n;

sub foo {
  print foo: $Self\n;
}

1;
__END__


# bar.pm

my $Self = __FILE__;
print bar: $Self\n;

sub bar {
  print bar: $Self\n;
}

sub super_bar {
  our $Self;
  print super_bar: $Self\n;
}

1;
__END__



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Parameterizing a module

2005-12-07 Thread Shawn Corey

[EMAIL PROTECTED] wrote:

In my script, I load the module by saying use PerlMQ;. However, now I want to
load only certain use statements from the module depending on the parameter I
give it. For example, in my script, I want to say use PerlMQ
qw(some_parameter) in order to load the use statements specified by
some_parameter in the module. Is it possible to do that?


Yes, there are ways.

 
--

 #PerlMQ.pm

 use strict;
 use warnings;

 use statement1;
 use statement2;
 use statement3;


# Change to:
use File::Basename;

use if ( basename( $0 ) eq 'script1' ), module1 = undef;
use if ( basename( $0 ) eq 'script1'
  basename( $0 ) eq 'script2' ),
   module2 = undef;
use if ( basename( $0 ) eq 'script3' ), module3 = undef;

 #and so on...

 1;

 _END_


See `perldoc if` for details.

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Extract text from file

2005-12-07 Thread Shawn Corey

Andrej Kastrin wrote:

Hello dears,

I have a file in row data format, which stores different terms (e.g. 
genes) and look like:


ABH
HD
HDD
etc.


Then I have second file which looks like:
--
ID-  001 #ID number
TI-   analysis of HD patients. #title of article
AB- The present article deals with HD patients. #abstract

ID-  002 #ID number
TI-   In reply to analysis of HD patients. #title of article
AB- The present article deals with HDD patients. #abstract
--
etc., where the separator between records is blank line.

Now I have to extract  those ID, TI and AB fields from the second file, 
which involves any term in the first file.


Colleague from BioPerl mailing list helps me with the following code:

#!/usr/bin/perl

use strict;
use warnings;

my $file_terms = shift;
my $file_medline = shift;
open (TERM, $file_term) or die Can't open TERM; #open list of terms
open (MEDL, $file_medline) or die Can't open MEDL; #open records file

my @terms = TERM;

while (my ($pmid, $ti, $ab) = split MEDL) {
for my $term (@terms) {
if (/$term/ for ($pmid, $ti, $ab)) {
print $pmid\t$ti\t$ab;
}
}
}   



I'm little confused now, while above example doesn't work and I don't 
know why (compilation error in 15th and 19th line).

I'm still learning...


So aren't the folks at BioPerl.

Question: Do you want to extract just the fields or the full record if a 
field contain terms from file 1? The following will print the entire record.


#!/usr/bin/perl

use strict;
use warnings;

my $file_terms = shift;
my $file_medline = shift;
open (TERM, $file_terms) or die Can't open $file_terms: $!; #open list 
of terms
open (MEDL, $file_medline) or die Can't open $file_medline: $!; #open 
records file


chomp( my @terms = TERM );

{
  local $/ = \n\n;

  while( my $record = MEDL ){
print $record if grep { $record =~ /\b$_\b/ } @terms;
  }
}

__END__



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Extract text from file

2005-12-07 Thread Shawn Corey

Andrej Kastrin wrote:
and additional question: how does Perl know where are the input files 
(while we only wrote: open (TERM, $file_terms) or die Can't open...)?


It comes from the command line. The statements:

  my $file_terms = shift;
  my $file_medline = shift;

are a shorten version of:

  my $file_terms = shift @ARGV;
  my $file_medline = shift @ARGV;

When a Perl script starts, the command line arguments are placed in the 
special array @ARGV. See `perldoc -f shift` and also see `perldoc 
perlvar` and search for ARGV.


For each field:

#!/usr/bin/perl

use strict;
use warnings;

my $file_terms = shift;
my $file_medline = shift;
open (TERM, $file_terms) or die Can't open $file_terms: $!\n; #open 
list of terms
open (MEDL, $file_medline) or die Can't open $file_medline: $!\n; 
#open records file


chomp( my @terms = TERM );

while( my $line = MEDL ){
  print $line if grep { $line =~ /\b$_\b/ } @terms;
}

__END__


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Extract text from file

2005-12-07 Thread Shawn Corey

Andrej Kastrin wrote:
I try your code; now I try to write each potential target in a record 
tab separated, like:

TI- xx HD x  AB- xxx HD x   #record 1
TI- yy AB x  AB- xxx AB x#record 2
etc...

So \t separated within record and \n separated  between records. I try with

for my $term (@terms) {
   if (/$term/) {
  print  $_\t;


s/\n/\t/g;
print $_\n;



but it's not OK.



You have to do a substitution.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Parameterizing a module

2005-12-07 Thread Shawn Corey

[EMAIL PROTECTED] wrote:

Thanks Shawn. But, in this case, how would we send a parameter to the module
from the calling script. The module can see the name of the calling script, but
I want to make my module available to other perl programmers, and let them have
the flexibility of deciding which use statements they want from the module.


Wait a minute. Someone's being silly. Unless you're talking about groups 
of modules, you (or they) should 'use' them by the original names. But 
to answer your question, change the main script as follows.


#!/usr/bin/perl

use strict;
use warnings;

BEGIN {
  our $use_parameter = 'secret_code';
}
use PerlMQ;

__END__


# PerlMQ

our $use_parameter;
use if $use_parameter eq 'secret_code', Module = undef;

1;
__END__



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: which is more effective between map and foreach?

2005-12-06 Thread Shawn Corey

Xavier Noria wrote:
This is kind of a holy war. Some people have that point of view, some  
don't. All depends on the way you read map. The disagreement is such  
that recently map was optimized in void context to avoid the  generation 
of the list.


As always, Benchmark.pm is your friend for speed comparisons. Memory  is 
no longer misused with map in void context, so make a choice  according 
to your personal preferences.


Write the code like you are going to lose your memory in six months. 
Which is more effective? The method you are most likely to remember when 
you have to maintain the code.


BTW, only optimize your code if your manager says it's too slow. 
Understanding what you wrote is more important than speed.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Help with eval (WAS: which is more effective between map and foreach?)

2005-12-06 Thread Shawn Corey

Jennifer Garner wrote:

And, I have another syntax question here. I can't know clearly the
difference between eval  and eval {}. I have run perldoc -f eval and
read it,but still can't know clearly.Can you help me on this?


eval {} or eval BLOCK is parsed only once at compile time. This means 
the Perl statements in it cannot change, only the values in the 
variables. eval  or eval EXPR is parsed every time it is encountered. 
This means the Perl program can be completely changed. For example, 
suppose we want a program that compares the content of a file to a 
series of patterns but the patterns are determined by the user at run 
time. We can do this with two loops:


  while(  ){
chomp;
for my $pattern ( @Patterns ){
  if( /$pattern/ ){
process_when_found( $_ );
  }
}
  }

We could use grep:

  while( my $line =  ){
chomp $line;
if( grep { $line =~ /$_/ } @Patterns ){
  process_when_found( $line );
}
  }

Or we could use eval

  my $expr = '/' . join( '/ || /', @Patterns ) . '/';
  while(  ){
chomp;
if( eval $expr ){
  process_when_found( $_ );
}
  }

eval EXPR is more flexible; eval BLOCK parses at compile time (meaning 
you, not the user, is notified of syntax errors).


Hopes this helps.

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: when do vars go out of scope in this case?

2005-12-06 Thread Shawn Corey

JupiterHost.Net wrote:
I'm thinking its B and and the best way to reclaim the memory in this 
case is to undef()ine $foo when its no longer used in the block.


I always thought B too. But don't forget you can use a block anywhere 
you can use a statement.



{


{


my $foo = load_100M_of_data();

print $foo; # $foo is using 100M of memeory ±



} # memory for $foo has been released

# A) $foo is now out of scope (and therefore no longer 100M of 
memory) since its not used anywhere after that print() in this block


# 100 lines of code without any use of $foo


} # B) $foo is now out of scope (and therefore no longer using 100M of 
memory)



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: when do vars go out of scope in this case?

2005-12-06 Thread Shawn Corey

JupiterHost.Net wrote:
Good idea Shawn :) the actual project is one thing, I'm really mostly 
curious if that is true or not, that its out of scope when its last 
referenced in a block instead of the end of a block.




I still think at the end of the block. Going out-of-scope when last used 
would mean the compiler would have to look far ahead (or do multiple 
passes), something most modern compilers do not.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Skip then print

2005-12-05 Thread Shawn Corey

Ron McKeever wrote:

I would like to skip the first ten lines of output from tail


If you want the last line of a file, you can get tail to print only 
that. See `man tail`.


$ tail -n 1 file

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: config files

2005-12-02 Thread Shawn Corey

M. Lewis wrote:
I'm trying to move the configuration variables out of three perl scripts 
and put them in a config file. Fine, no problem so far.


The way this works is an email message with a given subject is processed 
by procmail then passed off to the first perl script. The first script 
sets up the second. The second sets up the third script.


If at the command line I do './script1.pl  my_email_message.eml 
everything works fine. The three scripts fire off as they should and do 
their tasks.


However, if allowed to be processed as normal (started via an incoming 
email message), then it does not work.


The root of the problem is I read the configuration file in script2.pl 
thusly:


do './mcr.conf';

The only way I have found thus far to make this work via the 'normal 
route' of an incoming email message is to change the above line to:


do '/absolute/path/to/mcr.conf';

Which defeats my purpose of getting the configuration items out of the 
scripts themselves. I don't want the users to have to edit the three 
scripts, only the mcr.conf file.


Is there a way around this?


Your problem could be one of two things.

1. The procmail is run by the user but not from the directory where 
mcr.conf is. Without forcing the user to start in this directory, you 
would have to put the path somewhere in the process; either in the Perl 
script or perhaps your procmail has an environment variable you can set. 
In UNIX, you can read the environment via %ENV. You can try:


  do $ENV{HOME}/path/from/user/home/mcr.conf;

2. The procmail is run when a new message is placed in the user's 
mailbox. In UNIX, this is done by a daemon with the uid mail. This means 
it has a completely different environment but it may set some 
environment variables before calling your script that describe what it 
is doing and who it is doing it for. In that case:


  my $user = $ENV{PROCMAIL_USER}; # Use the appropriate name
  my $home_dir = glob( ~$user );
  do $home_dir/path/from/user/home/mcr.conf;

Note that PROCMAIL_USER is just a guess. Consult the documentation for 
procmail to get the correct name.


I don't normally work in MS Windows, so I can't help you there but if 
you're willing to dig deep enough I'm sure you can find the equivalent 
somewhere the the documentation.


See:
perldoc -f glob
perldoc File::Glob
perldoc perlvar (search for ENV)


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Flushing Buffers (WAS: recursive search)

2005-12-02 Thread Shawn Corey

Jennifer Garner wrote:

$|=1;



Be careful with this one. The documentation for it makes it sound like 
it's a good idea to set this but doing so turns buffering OFF, not ON. 
Normally you leave this alone, even for pipes and sockets; Perl does the 
right thing in almost every case.


See:
perldoc perlvar (search for $|)
perldoc FileHandle


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Convert date to timestamp

2005-12-02 Thread Shawn Corey

Timothy Johnson wrote:

Correction:  That line should be:

my $perlTime = timelocal(01,01,01,$day,$month - 1,$year);


You should use noon, not midnight (or close to it).

my $unix_epoch = timelocal( 0, 0, 12, $day, $month - 1, $year - 1900 );

Here in North America (at least in most places) there is one day that 
has 25 hours and one that has 23 hours every year. Using noon, will get 
around most of the problems with this.


For more info, search the web for 'Daylight Saving Time'.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: recursive search

2005-12-02 Thread Shawn Corey

The Ghost wrote:

So far I did this:

#!/usr/bin/perl

use File::Find;
my $totalLines;
find(\wanted, '@directories');
sub wanted {
 unless ($_=~m/.html|.mas|.pl|.txt$/i) {return 0;} #filter the 
kinds  of files you want

 open FILE, $File::Find::name;
 print $_: ;
my @lines=FILE;
print $#lines\n;
$totalLines+=$#lines; #wanted's value is ignored so we have to  
do this here.


$#lines is the index of the last entry in @lines. scalar( @lines ) is 
the number of items in the array. Normally, $#lines + 1 == scalar( 
@lines ). I think you should use scalar( @lines ) here.



return;}
print $totalLines\n;

This only limits me by the size of the file, or no?


Yes. If you have big files, replace the slurp with a loop.

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: config files

2005-12-02 Thread Shawn Corey

Dr.Ruud wrote:

If the .conf is in the same directory as the .pl, then $0 can help, see
`perldoc perlvar` and File::Basename, or maybe even `perldoc FindBin`.


True. But since the OP said 'mail' I assumed that meant more than one 
user, each with a different configuration.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Referring to the calling script from a module

2005-12-02 Thread Shawn Corey

[EMAIL PROTECTED] wrote:

Is it possible for a module to refer to its calling script? For example, if I
create a module called MyModule.pm, and use it in a script MyScript.pl by saying
use MyModule;, is it possible to refer to the calling script (MyScript.pl in
this case) and get some information about it during the process of writing the
module (MyModule.pm in this case)? This way, I want to make the behaviour of the
module flexible based on where it is called.


Modules are not called; they are loaded. Subroutines in modules are 
called. Unless requested, I shan't get into the difference between 
compiling and running, yet alone modules, packages, and objects.


You can refer to the script name with $0. You could also do something 
like this:


# In the script
BEGIN {
  our $ScriptName = 'myscript';
  our @ModuleNames = ();
}

our @ModuleNames;
use mymodule;

__END__


# In each module
our @ModuleNames;
push @ModuleNames, 'this_module_name';

# Alternate
our @ModuleNames;
use File::Basename;
push @ModuleNames, basename( __FILE__ );

1; # All modules must return a non-false value
__END__


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Help with syntax local (*in);

2005-12-02 Thread Shawn Corey

Buehler, Bob wrote:

local(*in);

Does this indicate that you want to make all variables that begin with
$in private?



No.

Perl has two kinds of scoping: lexical and dynamic. Lexical scoping 
means the name only has meaning with the block, or if outside any block, 
within the file. Dynamic scoping means within the block and in any 
subroutine called in the block. The keyword local is used to set dynamic 
scoping. For example:


open FILE,  myfile.txt or die 'cannot open myfile.txt: $!\n;
my $contents = '';
{
  local $/;# set $/ to undef
  $contents = FILE;  # slurps the entire file, \n's included
}
# End of block, $/ reset to whatever it was before.
close FILE;

Here dynamic scoping is used as a stack to preserve $/ while the file is 
slurped.


In 'local(*in);' the phrase '*in' is a typeglob. It means every 
identifier 'in'. This includes $in, @in, %in, sub in, and file handler 
'in'. Localizing 'in' would set all of them to undef.


To privatize a variable, use 'my'. Try this example:

#!/usr/bin/perl

use strict;
use warnings;

my $var = 'This is a test.';
print $var\n;

{
  my $var = 'foobar';
  print $var\n;
}

print $var\n;

__END__

'my' privatizes $var to the file and to the block while inside the 
block. You would have to use 'our' (in both files) to get a global 
variable shared between files.


You will have to experiment with 'my', 'our', and 'local' to see exactly 
what they do; an full explanation is beyond a simple e-mail.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Count number of times matched

2005-12-01 Thread Shawn Corey

SG Edwards wrote:
If I want to count the number of times that a match occurs in a line is 
there a way of doing this, if there is I have not found it!


e.g.
$line=This is a sentence about matching sentences.\n;

$line=~/sentence/ig;

So I will have matched sentence twice and I want to record this.

I can do it like this:

$line=~/sentence/ig;

# count the number of instances of this in the sentence
@split=split(/sentence/,$line);
[EMAIL PROTECTED];
$length--;


This code works fine, but if I need to keep each matched term (as I have 
wild-cards to capture spelling variants).


i.e. output would be:
sentence
sentece

Is there a way to automatically capture each individual match (e.g. 
using a special array character?)


Is this close to what you want?

#!/usr/bin/perl

use strict;
use warnings;

my $line = This is a sentence about matching sentences.\n;

my $count = 0;
while( $line =~ /(sentence\w*)/ig ){
  my $lexical = $1;
  $count ++;
  print $count. $lexical\n;
}
print \ttotal: $count\n;

__END__


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Adding the use statements to a different file

2005-11-28 Thread Shawn Corey

[EMAIL PROTECTED] wrote:

Hi,

I have to write several perl scripts with a number of modules included.
Therefore, I have to type many use statements at the top of each script. Is
there a way to dump all these use statements in a different file and then just
include that file everytime I have to include these use statements?

I know that writing a module is a great way to do something like that, but
doesn't a module export variables and subroutines? How can I make a module
export use statements?


Perl has three distinct ways of separating content: modules, packages, 
and objects. Modules do not export variables and subroutines; packages 
do. Or to be specific, packages can export variables and subroutines to 
the main package.


You can use a module as a straight-forward include. Simply list the 
material you want and it will be including in the package where the 
'use' command is.


In the main file:

use MyUseList;

Create a file called MyUseList.pm and add your list.

#!/usr/bin/perl

use strict;
use warnings;

# Your list goes here

1;  # Modules must return a non-false value
__END__


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: how to interupt a running program

2005-11-21 Thread Shawn Corey

S, karthik (IE03x) wrote:

I need to control a perl program from another perl program.


See:
perldoc perlipc (search for Signals)
perldoc perlvar (search for %SIG)
perldoc -f kill

Also:
perldoc -f fork
perldoc -f wait

The kill function sends a signal to another process, it does not 
necessarily kill it. How the process responds to the signal is its 
business. The only except is the KILL signal (signal number 9) which 
always kills the process. Unfortunately the function to send signals to 
other processes is called kill, which leads to lots of confusion.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Execute newgrp system command

2005-11-21 Thread Shawn Corey

Suvajit Sengupta wrote:

Hi,
 I want to login into a new group using 'newgrp' UNIX command.Every 
newgrp command invokes a new shell.
But when I am trying to execute this system command from a perl script 
the script is terminating and returning the prompt of the new shell .
Can anyone suggest on what can be done to change into a new group from 
within perl script?


Short answer: You can't.

Long answer:

The newgrp command will always run a new shell regardless if it succeeds 
or fails. What you can do instead is set the effective group id for the 
script.


1. Change the script's group to the group you want it to work under (see 
`man chgrp`).


2. Change the script's set group id on execution flag (see `chmod`).

The script will now run under the new group.

See `perldoc perlvar` and search for $) and $(.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Modifying column values of file records and appending to end of file.

2005-11-21 Thread Shawn Corey

Danny Fang wrote:

  However, I'm not sure how I could rewrite the newly modified column values of 
that particular row back into the file - I want to use the particular row which 
had its columns modified to be duplicated and appended to the end of the 
current file for a specific number of time (adding more rows with the 
duplicated rows).


It is considered bad form to write back into a text file since a change 
of length of one byte in a record could screw-up the rest of the file.



#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

   
  ##open file for reading

open(INPUTFILE, $inputFile) || die Cannot open $inputFile \n;


# Is $inputFile tainted? That is, is it hard-coded
# or a user given value. To protect yourself from
# malicious users, use:

open INPUTFILE,  $inputFile or die ...;

# If you don't see why, ask yourself what if the
# user gives ~/.profile as the $inputFile?
# What if he gives rm -fr * |?


  @fileRecs = INPUTFILE;
$totalRecs = scalar(@fileRecs)-1;
  print Total records in $inputFile is $totalRecs  \n;
  ##open file for writting output

  open(OUTFILE, $inputFile.tmp) || die Cannot open $inputFile.tmp \n;
  $secondRow = $fileRecs[2];
print BEGINNING -- secondRow = $secondRow \n;
 
@secondRowRec = split(|, $secondRow);
   
   $secondRowRec[2]=;

   $secondRowRec[3]=B;


# Now put the record back together.
$secondRow = join( |, @secondRowRec );
$fileRecs[2] = $secondRow;



  print \$secondRowRec[2] = $secondRowRec[2] and \$secondRowRec[3]=$secondRowRec[3] 
\n;
  
print \$secondRow is now $secondRow \n;
   
  $diffOfNewRec = 4000 - $totalRecs;


  print Need to produce additional $diffOfNewRec \n;
   
  #making a backup copy

  `cp $inputFile $inputFile.tmp`;


# Bad idea. You have just opened $inputFile.tmp for writing. Try:
use File::Copy qw( copy move );
copy( $inputFile, $inputFile.bak );

   
   
  ## I'm need help here !! Not sure how I could re-join the elements modified back into the array containing that particular row and append it to the end of the file

  ##
  print OUTFILE for ($i=0;$i$diffOfNewRec; $i++){
   print OUTFILE $secondRow\n;   
}
   
  close OUTFILE;


for my $rec ( @fileRecs ){
  print OUTFILE, $rec or die cannot write to output: $!;
}

# To speed up processing, the computer stores
# up file writes in a buffer and only
# writes when it is full. The close command
# will write the last little piece in the buffer
# and should be tested for error.
close OUTFILE or die cannot write to output: $!;

# Now move the new file to the old.
move( $inputFile.tmp, $inputFile );

__END__

You mentioned that you want to add more records to the end but you 
haven't indicated what they are.




--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Hi All

2005-11-16 Thread Shawn Corey

Randal L. Schwartz wrote:

Hridyesh == Hridyesh Pant [EMAIL PROTECTED] writes:



Hridyesh Check this site http://perldoc.perl.org/

Why refer someone to a website that replicates everything that is on
their own disk anyway?  It boggles my mind every time I see this!



Because searching perldoc really, really sucks. The only search 
available is `perldoc -q keyword` and it only searches the FAQs and 
then, only their questions. That's right, only the questions; the 
answers are skipped!


If you want to make perldoc useful, why don't you organize a project to 
go thru its PODs and add X... where appropriate?



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: about regex

2005-11-16 Thread Shawn Corey

Elie De Brauwer wrote:
You could for example do that by buffering them. Following example reads 
from standard input. No that you should replace the regexp by something 
with more meaning in your context. This application also assumes that 
there will be at least three lines of input.


my $a=STDIN;
chomp $a;
my $b=STDIN;
chomp $b;
my $c=STDIN;
chomp $c;
while($c !~ /-1$/){
$a=$b;
$b=$c;
$c=STDIN;
chomp $c;
}
if($c =~ /-1$/){   
print $a\n$b\n$c\n;

}else{
print Not found\n;
}

hth
E.


You could keep a sliding list of lines:

#!/usr/bin/perl

use strict;
use warnings;

my $kept_lines = 3;
my @lines = ();

while(  ){
  push @lines, $_;
  shift @lines if @lines  $kept_lines;
  chomp;
  if( /:-1$/ ){
print @lines;
  }
}

__END__



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Linked Lists in Perl

2005-11-16 Thread Shawn Corey


Handling linked lists in Perl is not the same as in C. You can emulate 
them with arrays and manipulate them by using Perl's array functions.



Create a list:   my @list = ();
Clear the list:  @list = ();
Add an $item:push @list, $item;
Remove an $item: $item = pop @list;
Add an $item to the other end:   unshift @list, $item;
Remove an $item from the other end:  $item = shift @list;
Get its size:$size = scalar( @list );
Retrieve the first $item:$item = $list[0];
Retrieve the last $item: $item = $list[-1];
Retrieve $n items from position $i:  @items = @list[ $i .. $i+$n-1 ];
Remove $n items from position $i:@items = splice( @list, $i, $n );
Insert @items at position $i:splice( @list, $i, 0, @items );
Reverse the list:@list = reverse @list;
Rotate the list: push @list, shift @list;
Reverse rotate the list: unshift @list, pop @list;


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: What is $ (can´t find it in the Camelbook)

2005-11-10 Thread Shawn Corey

Elie De Brauwer wrote:

Angerstein wrote:


Hello there,
I found the $ Scalar in some examples but I can´t figure out what 
they are

for.

Could someone tell me what $ is?




perldoc perlvar
 $LIST_SEPARATOR
 $  This is like $, except that it applies to array and slice val-
 ues interpolated into a double-quoted string (or similar inter-
 preted string).  Default is a space.  (Mnemonic: obvious, I
 think.)

hth
E.



It's the string Perl uses to separate array values when expanded inside 
a double-quoted string.


#!/usr/bin/perl

use strict;
use warnings;

my @array = qw( a b c );
$ = ', ';
print @array\n;

__END__



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Is it possible with RegEx

2005-11-10 Thread Shawn Corey

Gilles wrote:

Hi,

I try do to a  simple  thing :

Knowing If a string like 13 exist in a string like 123

Or if 37 exist in 12356789

I tried many solutions, but never found one good so I try to do it with
loops which more difficult but not impossible

I'd like to know if with RegExp  it's more simply


No, it's not possible with RegExp. What you want is called the Longest 
Common Subsequence. See http://www.ics.uci.edu/~eppstein/161/960229.html 
for a description of the algorithm. There are a number of modules in 
CPAN http://search.cpan.org/ under LCS 
http://search.cpan.org/search?query=lcsmode=module but since I don't 
use any, I won't recommend any.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: system command help

2005-11-10 Thread Shawn Corey

Marilyn Sander wrote:


On Nov 9, 2005, at 4:52 PM, Pablo Wolter wrote:


The system function call returns a boolean value as return value, I don't
remember if 1 is for fail and 0 for success or viceversa.



Actually it is not a boolean value.  It is a two-byte value, and each
byte is an integer.  You need to look up the system() function in
some Perl documentation.  If you get two bytes of zero back, that
means system() and the command it invoked ran successfully.  If you
get a non-zero value, the lower byte indicates what error was found
in the Perl run-time;  the upper byte is the return code from the
command executed by system().


Actually, it's not a boolean nor a two-byte value. To describe it in C 
terms: it is a union of an integer and a packed struct; the struct is an 
integer, a bit, and an unsigned char.


How to Use system():


First decide if you want to use your shell as an interpreter. To use 
your shell, call system() with a single string containing the command.


  system( 'ls *' );   # system( 'dir *' ); for MS DOS

All the rules about meta-characters and quoting in the shell apply. If 
you don't want to use your shell, call system() with a list. (This is 
recommended for cross-platform scripts since you don't know what shell 
the user may be running.)


  system( 'ls', '*' );  # system( 'dir', '*' );

See `perldoc -f system` and `perldoc -f exec` for details.


Determining If system() Worked:
---

The system() function returns a value that is also contain in the 
special variable $? or $CHILD_ERROR if you had `use English;`. First, 
test it to see if the program could be started.


  system( 'Some_string_that_is_not_a_real_program' );
  die cannot start system: $! if $? == -1;

Note that the special variable $! (or $OS_ERROR) contains an English 
string describing the error.


Now, break up the structure of the value.

  my $exit_status = ( $?  8 );
  my $created_core_file = ( 0x80  $? );
  my $terminating_signal = ( 0x7f  $? );

The $exit_status is the exit value of the program. See `perldoc -f exit` 
and `man 3 exit`.


The $created_core_file is true if the program created a core file. Core 
files contain the program and the data at the time of termination. 
Special programs like debuggers can be used to view this file. If your 
program contains sensitive data, it is important to remove this file as 
soon as possible. Leaving core files lying around is a security risk. MS 
DOS almost never leaves a core file.


The $terminating_signal is the signal that caused the program to stop. 
Normal termination is zero. Other signal can be found in `man signal`. 
If this is non-zero, the program was interrupted before its task was 
completed. You may have temporary files or partial results hanging 
around. MS DOS does not have signals, so this is always zero.



Using system(), Simplified:
---

The simplest way to use the system() function is just to test the 
returned value for zero. If it is, the call worked.


  system( ... ) == 0 or die system call failed;



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: Getopt::Long

2005-11-08 Thread Shawn Corey

Chris Knipe wrote:

So, this is more of a block question I think, but how I can get the above
example to show the help screen FIRST, and THEN complain about the missing
value for -s 


Why?

Here's an example of how to do it:

#!/usr/bin/perl

use strict;
use warnings;

use File::Basename;
use File::Copy 'copy';

my $TmpDir = '/tmp';  # Change to 'C:\TEMP' for MS DOS

my $Self = basename( $0 );
my $SaveOutFile = $TmpDir/$Self.$$.out;
my $SaveErrFile = $TmpDir/$Self.$$.err;

open SAVE_OUT, STDOUT;
open SAVE_ERR, STDERR;

my $umask = umask 0600;
open STDERR,  $SaveErrFile;
open STDOUT,  $SaveOutFile;
umask $umask;

my $string = '';
unless( GetOptions(
  'help'  = \ShowHelp,
  'b=s'   = \$string,
)){
  open STDOUT, SAVE_OUT;
  open STDERR, SAVE_ERR;
  copy( $SaveErrFile, STDERR );
  copy( $SaveOutFile, STDOUT );
  ShowHelp;
}

if( $string ){
  open STDOUT, SAVE_OUT;
  open STDERR, SAVE_ERR;
  copy( $SaveErrFile, STDERR );
  copy( $SaveOutFile, STDOUT );

  # Place string munging here

}else{
  open STDOUT, SAVE_OUT;
  open STDERR, SAVE_ERR;
  ShowHelp;
  copy( $SaveErrFile, STDERR );
  copy( $SaveOutFile, STDOUT );
}

__END__


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: processing at preset times

2005-11-08 Thread Shawn Corey

Frank Bax wrote:
I realise that my subject line might suggest use of cron, but this is 
not workable unless there is some way for two scripts to communicate 
with each other.  If this could work, the processing script would 
probably still need a thread to do communication with timer script anyway.


Actually, using cron may not be a bad idea. There is nothing like having 
a 100 hour job crash after 99 hours and 59 minutes. If you can, consider 
rewriting the program so it works in small chunks. Use cron to restart 
the program at regular intervals. You can get the status of the process 
by examining the state of the temporary files, using another cron job. 
Even if you have a power failure, the process will be restarted when the 
computer reboots. An added bonus is you don't have to login in the wee 
hours of the morning just to make sure the program is still running.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: waitpid() and exitcode 8 ?

2005-11-07 Thread Shawn Corey

Elie De Brauwer wrote:

Hello list,

I recently encountered a small oddity.  Suppose I have a process A:

#!/usr/bin/perl

use strict;

print Hello \n;
sleep 1;
print Goodbye\n;
exit 9;

Simply shows some out and gives a certain exit code. A second process, 
simply calls fork, execs the child in a process and waits for the child 
in the other process. In Perl this can look like this:


my $cmd = /home/user/proces.pl;
my $pid = fork();


die cannot fork unless defined( $pid );


if($pid == 0){
print Hi I'm a child\n;
exec $cmd or die Failed to run $cmd\n;
}else{
print Hi I'm a parent waiting for child with PID: $pid\n;
my $ret = waitpid($pid,0);
print $pid exited with code . ($?8) .\n;
}

The oddity i located in the last line. It seemd that I had to divide $? 
by 256 (or shift over 8 positions to the right) to get the correct exit 
code. So my question is:

a) Is there an other way to wait for a child to die and get the exit code
b) Can someone explain the odd behaviour of the exit code ?

greetings
E.



The lower 8 bits are flags that tell you the conditions under which the 
child stopped. It could be normal termination, halted by signal (TERM or 
HALT), and if there is a core file. (Core files contain both the program 
and data at the time of termination. If the program was working on 
sensitive data and you're clever enough, you can read this data. Leaving 
core files lying around is a security risk.) Normally, Perl programs 
just ignore these flags.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: array of hashrefs

2005-11-06 Thread Shawn Corey

Octavian Rasnita wrote:

Hi,

I have tried the following test program:

my @array = (
{a = 'aaa', b = 'bbb',},
{a = 'ala', b = 'bala',},
);

my @array2 = @array;

$array2[0]{a} = 'nanan';
push(@array2, 'test');

use Data::Dumper;
print Dumper [EMAIL PROTECTED];

The result was:

$VAR1 = [
  {
'a' = 'nanan',
'b' = 'bbb'
  },
  {
'a' = 'ala',
'b' = 'bala'
  }
];

I know why modifying an element from a hashref from the second array
modifies that element in the first array and why the new pushed element in
the second array is not shown in the first array, but I don't know how to
create a second array with all the elements of the first one, but totally
separately.

Is this possible somehow, or I will need to use foreach element of the first
array, and create the correspondent element in the second one?
The array doesn't have more levels, so I would like avoiding using a CPAN
module that can copy an entire data structure.

Thank you.

Teddy




You can use the typeglob to modify the symbol table so that the two 
arrays are synchronized but it does not work with 'my' variables:


#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

our @array = (
  {a = 'aaa', b = 'bbb',},
  {a = 'ala', b = 'bala',},
);

our @array2;
*array2 = [EMAIL PROTECTED];

$array2[0]{a} = 'nanan';
push(@array2, 'test');

print Dumper [EMAIL PROTECTED];
print Dumper [EMAIL PROTECTED];

__END__

BTW, use this one sparingly; it will confuse a lot of people.

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: about cron and perl

2005-11-04 Thread Shawn Corey

ZHAO, BING wrote:

Hi,
  I was advised to check out man cron for how to use cron. Set 
off do_it.pl using cron. But that's about it , all I can get from web 
help. I have no clue:
  1. what should I include in the do_it.pl, say to delete 
certain old files?
  2. this is a more unix problem, how should I exactly invoke 
crontab do_it.pl, say I want cron to run do_it.pl everyday?

   thank you all.

best,



You should also check:

man crontab
man 5 crontab

cron is started at boot time and normally you have nothing to do with 
it. Also:


1. Your crontab is ran under your userid but not in the same 
environment. Do not rely on the environment variables PATH, MANPATH, 
HOME, or USER to have any values.


2. All output to STDOUT and STDERR is collected and sent to your mail. 
This may or may not be connected to your GUI email application. Consult 
your sysadmin on how to do this.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: What kind of structure to choice

2005-11-03 Thread Shawn Corey

Gilles wrote:

Hi,

I would like to create a matrix 9x9 where the elements are list (array).
(like a cube) 


These lists will decrease during processing and will normally contain one
element, so to know if a list is definitely treated I need a flag.

So 2 solutions seems to be good, but which one do you think will be easier
to use :

-  an array of array of array with as flag a special value at the
end of the last array

-  an array of array of hash with one key for the list of value and
one key for the flag

 


In the 2 solutions, I'm not sure to know how to access the lists I have to
modify !

 


Could you help me please

Thanks

Gilles


The best way to use a multi-dimensional array is to simply use it:

my @array = ();

# Adding an item to the $i, $j element
push @{ $array[$i][$j] }, $item;

# Retrieving an item
$item = pop @{ $array[$i][$j] };

# Accessing the $k item
$item = $array[$i][$j][$k];

# Iterating over a list
for my $item ( @{ $array[$i][$j] } ){
  # Any change to $item will change
  # the element in the list @{$array[$i][$j]}
}

# To see inside the matrix
use Data::Dumper;
print Dumper( [EMAIL PROTECTED] );


# For your other problem, I would simply keep a separate array.

my @Processed = ();

# for all $i, $j
unless( $Processed[$i][$j] ){
  # Process @{$array[$i][$j]}

  $Processed[$i][$j] = 1;
}


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: max value of an integer scalar

2005-11-03 Thread Shawn Corey

Adriano Ferreira wrote:

But the multiplication operator (*) is smarter and does an upgrade
from integer to floating point when needed, (possibly) increasing the
range of the correct results.

Adriano.



What JeeBee has stumbled across is a field of study called Numerical 
Analysis. For a brief introduction see 
http://en.wikipedia.org/wiki/Numerical_analysis


You are correct in that the multiplication operator automatically 
converts from integer to float for large values of $p but JeeBee needs 
an integer algorithm. For example, he uses ($p-1) % 3, which is only 
defined for non-negative integers. The problem is for large values of 
$p, $p == $p - 1. This is because floats only store a fixed number of 
digits. For example, if it stores 3 digits and $p = 1_000_000, then $p-1 
is 1.000e6 - 1 or 1.000e6. The one's column has dropped off the bottom; 
it is too small to be recorded in the float.


I recommend that JeeBee takes his algorithm to a mailing list on 
Numerical Analysis. They will have a lot more experience with the 
foibles of computers doing simple arithmetic.



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: XML Help

2005-11-03 Thread Shawn Corey

Scott Taylor wrote:

if ($x-{VEHICLE}-{STREETNUM}){ print ... }
else { print ; }

but even that doesn't work.

Cheers.

--
Scott



What do you mean when you say it doesn't work? Are you getting something 
like this?


Use of uninitialized value in concatenation (.) or string ...

If so, try:

if( defined( $x-{VEHICLE}{STREETNUM} )){
  print ... ;
}
# You don't need to print 

--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: statistics of text

2005-11-02 Thread Shawn Corey

Ing. Branislav Gerzo wrote:

I did this by hand...but anyone know how to this effectively in perl?
I think I have to build hash of all possibilities of 2 words sentences (in
input txt are allowed only [0-9a-z ]), in list I will have lines of
input txt, and iterate every key in hash over array, writing value to
hash its occurence (foo bar = 5)...hm ?




Not that this program reports that foo bar occurs twice on line 8.
bar bar - 2 times (lines: 4, 6)
bar foo - 3 times (lines: 5, 6, 8)
foo bar - 6 times (lines: 3, 4, 5, 7, 8, 8)
foo bars - 1 time (lines: 10)
foo foo - 1 time (lines: 7)
foob bar - 1 time (lines: 9)

To see the structure or %Pairs, uncomment the print Dumper line.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my %Pairs = ();

while( DATA ){
  chomp;
  my @words = split /\s+/;
  for( my $word = shift @words;
   @words;
   $word = shift @words
  ){
push @{ $Pairs{$word}{$words[0]}}, $.;
  }
}
# print Dumper( \%Pairs );

for my $first ( sort keys %Pairs ){
  for my $second ( sort keys %{ $Pairs{$first} } ){
my @lines = @{ $Pairs{$first}{$second} };
my $count = scalar( @lines ) .  time;
$count .= 's' unless scalar( @lines ) == 1;
print \$first $second\ - $count (lines: , join( ', ', @lines ), 
)\n;

  }
}

__END__
foo
bar
foo bar
foo bar bar
bar foo bar
bar bar foo
foo foo bar
foo bar foo bar
foob bar
foo bars


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: statistics of text

2005-11-02 Thread Shawn Corey

Ing. Branislav Gerzo wrote:

my $keyword = business;
my %all2words = ();
open TXT, words.txt or die $!;
while (TXT) {
chomp;


  next unless /\b$keyword\b/; # skip loop if no keyword


while ( /(?=(\S+\s+\S+))\S+/g ) {
my $temp = $1;
$all2words{$temp}++ if $temp =~ /$keyword/i;
}
}
close TXT or die $!;

for my $test ( sort { $all2words{$b} = $all2words{$a} } keys %all2words ) {
print $test = $all2words{$test}\n;
}



--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: uninitialized variable

2005-11-01 Thread Shawn Corey

Adedayo Adeyeye wrote:

Hello,

I'm getting an error when trying to run a script. Part of the scripts is

Line 10 my $action = param('form_action');

 .

 Line 14 Search_DB()  if($action eq 'search');

The error I get is:

 


[Tue Nov  1 16:28:41 2005] connect_script.cgi: Use of uninitialized value in
string eq at connect_rodopi.cgi line 14. 

 


How am I supposed to initialize this value?

 


Kind regards

 


Dayo

 

 






Two things you can do:

line 10: my $action = param('form_action') || '';

or

line 14: Search_DB() if( defined( $action )  $action eq 'search' );

The first solution implies that the value '' for $action will never be 
tested for. I prefer the second one. You can always put it in its own if 
statement:


if( defined( $action )){
  # list of actions
  ...
  Search_DB() if $action eq 'search';
  ...
}else{
  # page for no action
  ...
}


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: How to change the Owner of a file

2005-10-31 Thread Shawn Corey

Rakesh Mishra wrote:

Hi folks
Can any body tell me how to change the owner of a file ??

I have written this script ...

unless (chown $uid , $gid , $filename)
{
die chown failed :$!;
}

this code will give me the error you can't change  permission denied 
can any body tell me , how to over come this error

bye
rakesh



Yes, you must the the recipient of the change, unless you have superuser 
privileges. In other words, you must be $uid. This is because many UNIX 
systems have quotas on how much data you can store. To borrow someone 
else's capacity, create your file and chown to someone who doesn't have 
much data stored. If it has read-access for everyone, you can get the 
file back by copying it. Unfortunately the new version of chown prevent 
this.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: How to change the Owner of a file

2005-10-31 Thread Shawn Corey

Chris Devers wrote:

What??

That's hardly why this constraint exists.

If anyone can make changes to any other account's files, then there's no 
point in having ownership constraints at all. 


Of course. I was being facetious.



The new version of chown prevents what?


New is a relative term. I have worked with systems where the /dev was 
writable by anyone and the raw devices readable! When I pointed this out 
to the sysadmin I was told it can't be changed since some of the system 
utilities require this; they didn't run in superuser mode. Needless to 
say (but I'm going to anyhow) I only kept what was absolutely necessary 
on that system. Modern systems haven't had this problem for decades and 
security is given much more consideration than back then.


And yes, back then chown worked exactly as I described; you could use it 
to borrow some else's quotas. Given the small size of the disks, this 
was not an uncommon practice.


BTW, (and this is really going to date me) I do have a copy of the B 
Language Manual.


--

Just my 0.0002 million dollars worth,
   --- Shawn

Probability is now one. Any problems that are left are your own.
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response