Re: the only difference is the 'x' after '/g'

2006-03-31 Thread Hans Meier (John Doe)
tom arnall am Freitag, 31. März 2006 09.56:
> i need the blank in 'From [' etc in order to distinguish it from the
> strings with 'From:' one solution to the problem, btw, is to use '\s'
> instead of a literal blank. does this behavior rank as a bug in perl?

No, absolutely not. 

To make your distiction, you *have* to use the \s with the /x modifier; 
without, you can use either.

The /x modifier's aim is to allow readable *formatting* of complex regexes 
with spaces, line brakes, comments (#). ' ' in this case is irrelevant for 
the matching. Look at the beginning of 

perldoc perlre

hth!

Hans

[bottom post order:]
> On Thursday 30 March 2006 05:15 am, Hans Meier (John Doe) wrote:
> > tom arnall am Donnerstag, 30. März 2006 12.36:
> > > the following code:
> > >
> > >   my (@main);
> > >   $_="
> > >   From a
> > >   From: b
> > >   From: c
> > >   From: d
> > >   ";
> > >   @main = /From [^\n]*?\n.*?(From: .*?\n).*?/gx;
> > >   print "@main";
> > >   print "--\n";
> > >   @main = /From [^\n]*?\n.*?(From: .*?\n).*?/g;
> > >   print "@main";
> > >
> > > produces:
> > >
> > >   From: b
> > >From: d
> > >   --
> > >   From: b
> > >
> > > the only difference between the two regex lines is the 'x' after '/g'
> > > in the first of the two regex lines.
> >
> > indeed :-)
> >
> > And your question could be: Why does this produce different results?
> >
> > There's an additional difference on the semantic level: spaces in the 1st
> > regex are irrelevant. Look at the first regex space: in the 2nd regex, it
> > matches (only) in "From a", but not in "From: c", whereas the 1st regex
> > matches "From a" *and* "From: c".
> >
> > /From[^\n]*?\n.*?(From: .*?\n).*?/gx;
> > and
> > /From[^\n]*?\n.*?(From: .*?\n).*?/g;
> > produce both the same output.
> >
> > hth!
> > Hans

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




Re: Counting specific elements in a XML object

2006-03-30 Thread Hans Meier (John Doe)
Bob Showalter am Donnerstag, 30. März 2006 23.32:
> Chas Owens wrote:
> > If we are going to pick nits then it should be
> >
> > grep -c "" fn
>
> Note that grep -c counts matching *lines*. There is no formal
> requirement that these elements appear on separate lines.

Dave, 

my first one-liner suffers from the same (also only counts lines)

> Here's a slightly more complex Perl one-liner that counts *occurences*
>
>perl -lne '$n++ for //g; END {print $n}' somefile.xml

Bob,

thanks, I thought about the -n option, but missed the END block idea to 
finally print the sum.

(And again, problems that seem to be trivial are not in many cases...)

Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Counting specific elements in a XML object

2006-03-30 Thread Hans Meier (John Doe)
Chas Owens am Donnerstag, 30. März 2006 22.35:
> > > cat fn | grep  | wc
[...]
> > grep  fn | wc
[...]
> If we are going to pick nits then it should be
>
> grep -c "" fn

too much work. 

c "" fn

But your alias may be different ;-)

Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Counting specific elements in a XML object

2006-03-30 Thread Hans Meier (John Doe)
Gavin Bowlby am Donnerstag, 30. März 2006 21.45:
> How about:
>
> cat fn | grep  | wc

When I posted a "cat | grep" the first (and last) time, several people got a 
well known heart attack :-)

grep  fn | wc

> as a non-Perl approach to the problem...
[...]

Agreed, but OT here ;-)

Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Counting specific elements in a XML object

2006-03-30 Thread Hans Meier (John Doe)
Dave Adams am Donnerstag, 30. März 2006 21.12:
> If I have a xml file like the following:
>
> 
> 
>     John Doe
> 43
> M
> Recieving
> 
> 
> Bob Gordon
> 50
> M
> Shipping
> 
>
>
> Is there some perl module out there that can help me get the number of
> employees or in other words, the number occurences of ""?
>
> I guess I can get it conventionally by reading in the file and doing a
> count every time the script encounters "".  But there must be an
> easier way.

Ok, let's start with:

perl -e 'while(){//&&$i++};print $i' < data.xml

Anybody with an easier way in the sense of
- less typing
- more understandable
- less module imports ;-)
?

[preconditions: nothing else to do with the input; no CDATA containing 
; valid XML; etc.]

Hans



--
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 only difference is the 'x' after '/g'

2006-03-30 Thread Hans Meier (John Doe)
tom arnall am Donnerstag, 30. März 2006 12.36:
> the following code:
>
>   my (@main);
>   $_="
>   From a
>   From: b
>   From: c
>   From: d
>   ";
>   @main = /From [^\n]*?\n.*?(From: .*?\n).*?/gx;
>   print "@main";
>   print "--\n";
>   @main = /From [^\n]*?\n.*?(From: .*?\n).*?/g;
>   print "@main";
>
> produces:
>
>   From: b
>From: d
>   --
>   From: b
>
> the only difference between the two regex lines is the 'x' after '/g' in
> the first of the two regex lines.

indeed :-)

And your question could be: Why does this produce different results?

There's an additional difference on the semantic level: spaces in the 1st 
regex are irrelevant. Look at the first regex space: in the 2nd regex, it 
matches (only) in "From a", but not in "From: c", whereas the 1st regex 
matches "From a" *and* "From: c".

/From[^\n]*?\n.*?(From: .*?\n).*?/gx;
and
/From[^\n]*?\n.*?(From: .*?\n).*?/g;
produce both the same output.

hth!
Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Does this script have the efficiency problems?

2006-03-09 Thread Hans Meier (John Doe)
Practical Perl am Donnerstag, 9. März 2006 09.50:
> Hello,
>
> I have a script,which run well at most time.This day I use it to analyse
> the files of 1.7G,it become very slow and can't get executed continuely
> anymore.When I run 'strace -p ' (here  is this script's PID),there
> is no output,it seems died.
>
> Here is my script:
>
> #!/usr/bin/perl
> use strict;
> use warnings;
>
> my $date=`date +%y%m%d`;
> chomp $date;
> my $dir="/home/datas/loginIP";# here stored about 140 files,which are
> totally 1.7G.
> my @files= glob "$date/*.ip";
> my (%low, %total);
>
> foreach my $file (@files)
> {
> open (FILE,$file) or die "$!";
> while()
> {
> next if /^192\.168\./;
> next unless /^(\d+\.\d+\.\d+\.)(\d+)/;
> $low{$1}{$2}=1 if $2 < 128;
>
> $total{$1}{$2}=1;
> }
> close FILE;
> }
>
>
> open (RESULT,">","dynamic.$date.re") or die "$!";
>
> foreach (sort { scalar keys %{$total{$b}} <=> scalar keys %{$total{$a}} }
> keys %total)
> {
> my $low = scalar keys %{$low{$_}};
> my $high = (scalar keys %{$total{$_}}) - $low;
>
> if ($low > 64 and $high > 64)
> {
> printf RESULT "%-25s%-20s\n", $_."0", $_."255";
> }elsif ($low > 64 and $high <= 64)
> {
> printf RESULT "%-25s%-20s\n", $_."0", $_."127";
> }elsif ($low <= 64 and $high > 64)
> {
> printf RESULT "%-25s%-20s\n", $_."128", $_."255";
> }
> }
>
> close RESULT;
>
> 
>
> The files handled by the script are looked as:
>
> 211.139.227.247:3088
> 220.181.31.245:1134
> 220.181.31.247:1126
> 220.181.31.248:1120
> 220.181.31.246:1071
> 220.178.47.2:977
> 221.11.26.219:961
> 221.11.26.220:934
> 210.31.76.252:911
> ...
> 
> Why this happen and how to resolve it? Any suggestion is welcome.Thanks.

Do you have sufficient memory to hold all data in a hash and sort it?
Does the box swap?

Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: counting scalar array elements question

2006-03-09 Thread Hans Meier (John Doe)
John W. Krahn am Donnerstag, 9. März 2006 03.36:
> Hans Meier (John Doe) wrote:
[...]
> > my @array;
> > #or:
> > my @array=();

[v--- this sidenote is wrong]

> > (sidenote: the second form must be used in contexts where the code is
> > persistent/preloaded and used several times, to ensure that @array is
> > always empty when the next execution hits the code again. Of course only
> > *if* it should start empty and not accumulate between executions)
>
> Are you sure about that?

Not after realizing that 'my' is used. I was fixated to 
a) not forgetting a side note that could be annotated, as I did in one of my 
last posts
b) the initialisation part =(), having a situation in mind I just had before 
in a mod_perl context, where, in template code, a variable got not reset due 
to a missing =(). 
   But it was... an our variable.
   And against the "my variable closure phenomenon" the =() is also useless.

So again thanks for a hint and of course my above statement is wrong.

> Do you really understand what my() does? 

yes I think so. Generally, when all brain is present and working :-)

Hans

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




Re: counting scalar array elements question

2006-03-08 Thread Hans Meier (John Doe)
> > From: Graeme McLaren [mailto:[EMAIL PROTECTED]
> > Sent: Wednesday, March 08, 2006 3:57 PM
> > To: beginners@perl.org
> > Subject: counting scalar array elements question
> >
> > Hi all, I have an array question:
> >
> > If I have a variable, $var, and it contains an array how would I be able
> > to
> > easily count the number of elements in the array?  I've tried creating a
> > new
> > array and pushing the original array on to it but that creates an array
> > of
> > arrays.
> >
> > Basically I have:

use strict;
use warnings;

> > my $var = [
> >  'a',
> >  'b',
> >  'c'
> >]

# shorter: 

my $var=[ qw/ a b c / ];

> > and I tried:

my @array;
#or:
my @array=();

(sidenote: the second form must be used in contexts where the code is 
persistent/preloaded and used several times, to ensure that @array is always 
empty when the next execution hits the code again. Of course only *if* it 
should start empty and not accumulate between executions)

> > push @array, $var;
> >
> >
> > and got:
> >
> > @array=[
> > [
> >'a',
> >'b',
> >'c'
> > ]
> >   ]

You probably got this AoA (array of arrays) by using 

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

The outer [] stems from the \ after Dumper.

The data structure of @array itself is only, formulated as list:
@array=( ['a','b','c'] )

An arrayref is a scalar (holding a reference to an array), so after pushing it 
to an empty array, you just get an array with one element, the pushed scalar.

> > Using my original array which is assigned to scaler, what I need is:
> >
> > @array = [
> > 'a',
> > 'b',
> > 'c'
> > ]
> >
> >
> > So I can do:
> >
> > my [EMAIL PROTECTED];
> >
> >
> > Can anyone shed any light on this or suggest a better way of doing this?
>
>Timothy Johnson am Donnerstag, 9. März 2006 01.06:
> You need to dereference your array ref.
>
> my $count = @{$var};

the same, shorter, but more hiding what's going on:

my [EMAIL PROTECTED];

> Or in some circumstances it might make more sense to explicitly use
> scalar context:
>
> my $count = scalar @{$var};

One of these circumstances would be for example, since print provides list 
context:

print scalar @$var;

Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: multistring replacement

2006-03-08 Thread Hans Meier (John Doe)
Eugeny Altshuler am Mittwoch, 8. März 2006 11.35:
> Hello!
>
> I have such problem, I need to make multistring replacement... How can
> I do this?
>
> I tried to make perl script which acquires file form STDIN and prints
> result into STDOUT
>
> cat file.html | ./myscript

That's one way to pass the file content to a script via the STDIN filehandle.
A shorter way is to pass the filename to the script:

$ ./myscript file.html

Try out this code:

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

open my $fh, $ARGV[0] or die "can't open passed file '$ARGV[0]': $!";

local $/; # to slurp the file at once
my $joined=<$fh>;

print $joined;

# end of script

See:
perldoc perlvar (for @ARGV and $/)
perldoc open

> I work with html-files and I want to convert them into necessory format.
> I want to delete all stuff before  and after ... Also I
> want to delete  tags that can be splitted to few strings...
>
> $joined = join("", <>);
> $joined =~ s/.*//ig;
> $joined =~ s/]*>//ig;
> $joined =~ s/<\/SPAN>//ig;
> $joined =~ s/]*>//ig;
> $joined =~ s/<\/FONT>//ig;
> $joined =~ s/]*>//ig;
> $joined =~ s/<\/BODY.*>//ig;
> $joined =~ s/STYLE="[^"]*"//ig;

Without testing, the main problems here are:
- the missing /s modifier: Your html has more than one line!
- use of .* (greedy) instad of .*? (non greedy)

Studying the regexp man pages will help you getting the right regexps. 
See perldoc perlre and others.

Here is some untested code: may do the expected or not :-)

($joined)=~$joined=~m,(.*?),is or die "no body";
$joined=~s,<(?:SPAN|FONT)[^>]*?>,,igs;
$joined=~s,STYLE\s*=\s*(["']).*?\1,,igs;

This code is just a "hack" and assumes correct html syntax as well as no '>' 
and '<' in tag attribues. Correct regexpes would be longer.

A more structured way to do such things is the usage of one of the html 
parsers on search.cpan.org. Some of them can deal with erroneos html, others 
can not.


hth,
Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




[OT] sanitize/sanitise ? [was: [regexp] Speaking of the /s modifier...]

2006-03-08 Thread Hans Meier (John Doe)
Adam W am Mittwoch, 8. März 2006 02.10:
> Hans Meier (John Doe) wrote:
> > Adam W am Mittwoch, 8. März 2006 00.49:
> >>Sorry, I'm relatively new to programming in general (perl is my first
> >>programming language), so I'm not sure what you mean by "sanitizing."
> >
> > Could also be "sanitising", saw both :-)
>
> I've seen it both ways, as well (I think it's a British vs. American
> distinction).  I did not mean to correct your spelling.  

Oh, I realize this interpretation only now!

> What I meant 
> was that I didn't understand the concept of "sanitizing" in a
> programming context.

Yes I read it this way, no problem! 

I was just wondering myself... and finally consulted the "Pons" dictionnary 
that only mentions "sanitize" but says it covers british / northamerican / 
australian vocabulary. 

But the british/american distinction seems plausible, since I also read 
"sanitise" from native english speakers (and in advisories from big companies 
if I remember correctly). 
Hm... anybody has the definitive answer (to this detail)? 

Wish you much fun programming!

Hans

[...]

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




Re: [regexp] Speaking of the /s modifier...

2006-03-07 Thread Hans Meier (John Doe)
Adam W am Mittwoch, 8. März 2006 00.49:
> Hans Meier (John Doe) wrote:
> > Adam W am Dienstag, 7. März 2006 23.16:
> >>Hans Meier (John Doe) wrote:
[...]
> > (this dies on empty lines etc. too, and of course the input file's lines
> > should be sanitizes before, and to be on the secure side, the
> > transformation script should do that too... but all that depends on the
> > exact circumstances you use the script)
>
> Sorry, I'm relatively new to programming in general (perl is my first
> programming language), so I'm not sure what you mean by "sanitizing."

Could also be "sanitising", saw both :-)

> Does this imply having the program correct any possible errors in the
> imput to be compliant with the way the program operates on the input?

Yes I think one could say so.

Sorry if the explanation is not good english:

Saniti(z|s)ing means to assure that all input from *outside* of the program 
(file content, environment variables, user input from cmd line / webinterface 
etc. etc) has the format that's being *expected*. Don't trust any data coming 
from outside.

Missing input sanitizing is the main reason for security holes in software 
applications (I think). (maybe you heard of XSS, buffer/integer/heap 
overflows, HTTP-Response Splitting, Cookie Theft and other terms).
   Simple example: A web based app that expects simple 
text to present on a web page; but user inputs some javascript; if not 
sanitised, the javascript is presented to the browser. 
   Another example: Many "Feedback-Form" scripts around sending mail are 
horribly programmed and allow the sending of spam. I have experience with it 
from my beginners time with an own script doing that... not fun... was 
expensive. I would not recommend to place any beginners code on a publicly 
accessible server without reviewing by others. Chances that it can be misused 
are very big (in my opinion, as usual).

Here comes in the "Taint Mode" of perl (perldoc -q taint as a start) which 
asserts that every data coming from outside is handled with a regexp; it 
can't garantee that you do the right thing, but that you *do* at least 
consider possible dangers.

I would recommend (from own bad experience) to start saniti.ing from the 
beginning. It's important on any system more than one user has access. Get 
used at it, as with toothcleaning and such.

[...]
> > Also no if $/ is set to something that reads more than one line.
> >
> > The $/ variable is very interesting for reading multiline records from a
> > file like conventional lines. Have a look at it!
>
>   Thanks for mentioning the '$/' variable, which is probably what I was
> looking for but didn't know existed (yeah, I know, RTF...)!

Unfortunately at the beginning it is not easy to know what all exists. One 
main purpose of manuals is to get information about something one knows 
exists; but If you have time, read and read and read to get an idea what's 
present; look at code; follow mailing lists; buy a perl book, there are 
extraordinary well ones around (for example "Programming in Perl", "Perl 
Cookbook", both from O'Reilly) - just keep in mind that most books present 
concepts and not practically usable stuff; you seldomly see input sanita.ing 
in the examples of such books.

> >>I eventually got around this problem by simply printing what I wanted
> >>after opening the file but before the while loop, and then printing
> >>again after the while loop had ended but before the next file is opened.
> >
> > Sorry, this is not clear to me (what's the purpose of the while in this
> > scenario?)
>
> The while is reading in a file, so it is in the while()
> context.  Here is the relevant (paraphrased) code:
>
>   print OUT "";
>   while (defined($lines = )) {
>   ...make the substitutions to the text...
>   print OUT $lines;
>   }
>   print OUT "";
>
>
> The p-tags are there because I want each list of links to be an HTML
> paragraph formatted according to my CSS definition of .  Nothing
> special.

Now it's clear; I thought you're talking about the transformation :-)

> > Nice way to post on this list; not the kind of "Oh, I spend 10 secs to
> > ask, there will be people spending 1/2 h to solve my problem".
>
> Thank you. Nothing helps a community more than communication.

True :-)

Hans

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




[getting OT?] Re: [regexp] Speaking of the /s modifier...

2006-03-07 Thread Hans Meier (John Doe)
JupiterHost.Net am Mittwoch, 8. März 2006 00.29:
> >> - "\(" instead of "[(]": more readable
>
> not according to "best practices

Hi JupiterHost.Net

I think there are more than one "best practices", although not several books 
carrying this title. I can't - and don't want to - diskuss based on 
"According to XYZ" (missing arguments), sorry.

Readability is good. Performance, as John W. Krahn added, is also good. In 
that case, I don't care about XYZ.

> >> - no /m modifier   : unnecessary without ^/$-anchors
>
> Still a good habit to get into according to 'best practices' (and to get
> used 

Getting used using unused usefullness is useless in my opinion ;-)

> to what it does to  \A \z and ^ $

Which is (in my opinion) better to achieve by using it when appropriate and by 
rtfm.

When everybody followed the advice "do $a to get used at it", there wouldn't 
be any perl one liner any more ;-)

> >> - /s   : may be appropriate for your html source text
>
> It only really affects making it easier to read by including spaces, any
> spaces to match would need put in your regex. So its appropraite for any
> regex that space will make clearer to understand and maintain :)

I suspect you don't talk about the /s modifier here...

> Sorry, I'm a huge fan of "Best Practices"

Yes, obviously, seen in another post already.

> I call it "the book that got 
> me my free mini convertable and got me a substantial promotion".

Sorry, too much for my english capabilities...

> but do what you like :) 

Thanks - you too :-)

[...]

Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: [regexp] Speaking of the /s modifier...

2006-03-07 Thread Hans Meier (John Doe)
Adam W am Dienstag, 7. März 2006 23.16:
> Hans Meier (John Doe) wrote:
> > just to sum up:
> >
> > $test =~ s{ (.*?)  \(  (.*?)  \) }
> >   {$1}xsg;
> >
> > - "\(" instead of "[(]": more readable
> > - no /m modifier   : unnecessary without ^/$-anchors
> > - /s   : may be appropriate for your html source text
> >
>
> The context for this regexp is a simple program I wrote to turn text
> files of the form:
>someword(http://www.linktosomething.com)
> to
>   http://www.linktosomething.com";
>   alt="http://www.linktosomething.com";>someword
> (without the linebreaks, of course).
> It works by reading in some text file, line by line, using while(<>).

That's ok, so no /s required :-)

Then you can even check if what should be on one line is effectively on one 
line, by:

$text=~/your_regex_here/x or die "improper line format: $text";

(this dies on empty lines etc. too, and of course the input file's lines 
should be sanitizes before, and to be on the secure side, the transformation 
script should do that too... but all that depends on the exact circumstances 
you use the script)

> Initially, I wanted the program to stick a  tag at the beginning of
> the file and a  tag at the end of the file.

That's going in the direction of an XML formatted file.
In my opinion, if you want to do that, you could store the input file data as 
XML and use an XML Parser or XSLT to transform the input data. Then you would 
not need regexes, but the hole thing would be blown up a bit :-)

> Is it possible to make 
> a regexp that will only match the beginning and ending of a file within
> a "while" loop?

Not directly. I can't see at the moment a way to do that without ugly code.

But what should be the sense of that in conjunction with /??

> It seems as though you cannot, since "while" only reads 
> in data line by line and thus, even if you remove the newlines from the
> input, you can only operate on one line of input at a time.  
> Is this correct?  

Not in all cases, see following paragraph.

> If it is, then would it be correct to say that, practically 
> speaking, while in a "while" loop, the presence or absence of a /s
> modifier will not effect rexep recognition?

In the while () case, and $/ (perldoc perlvar) set to newline: 
yes.

No when slurping all lines at once into an array and loop over the array.

Also no if $/ is set to something that reads more than one line.

The $/ variable is very interesting for reading multiline records from a file 
like conventional lines. Have a look at it!

I always think of lines in the present context as "meta-lines" or "virtual 
lines" ;-)

> I eventually got around this problem by simply printing what I wanted
> after opening the file but before the while loop, and then printing
> again after the while loop had ended but before the next file is opened.

Sorry, this is not clear to me (what's the purpose of the while in this 
scenario?)

> However, I remain curious about the function of /s in while loops.
>
> Just something I've been wondering about,

Nice way to post on this list; not the kind of "Oh, I spend 10 secs to ask, 
there will be people spending 1/2 h to solve my problem".
Thanks :-)

Hans

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




Re: Directory issue

2006-03-07 Thread Hans Meier (John Doe)
DiGregorio, Dave am Dienstag, 7. März 2006 19.30:
> Ok, I am trying to run another perl script from a perl script and have
> had little luck in doing so.  The main script is in one directory and
> the one it is controlling is in another directory.  the main script
> starts and calls the other script which is supposed to read a file.
> However, 

> I get can not find the "readfile" which is located in the same 
> directory as the script called by the first. 

I don't unterstand this part about "readfile" completely; do you call it from 
someScript.pl? And how?

> Now, if I run the called 
> script by itself the problem goes away and all is good.  So the problem
> I believe is caused by the CWD of the commanding script.  To get around
> this I tried:
>

You already got hints about the backslash in perl. Although, I would rewrite 
the code as follows:

> chdir("C:\Go\Here\") || die "cant not change dir\n" ;

chdir ('C:\Go\Here\') or die 'cant not change dir\n';

- No double qoutes needed because no variables are interpolated into strings
- 'or' has lower precedence than '||'

> system("perl someScript.pl -a createOperator -p f112a") || die "$_";

system('perl someScript.pl -a createOperator -p f112a') == 0
   or die "'system' failed: $?";

The same holds here about the double quotes (wich should be avoided in system 
calls anyway).

But the line has another two problems:

First, $? (not $_) contains the exit status of system.
Second, success in the shell is indicated by a return value of 0, which is 
true in the shell, but false in perl. So, this codeline dies always if system 
succeeded and never if it didn't.

I tried my above lines under linux, and everything was ok.



hth,
Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: [regexp] Warnings on Backreferences

2006-03-06 Thread Hans Meier (John Doe)
John W. Krahn am Dienstag, 7. März 2006 00.12:
> Adam W wrote:
> > JupiterHost.Net wrote:
>  $text =~ s!(.*?)\((.*?)\)!$1!g;
[...]
> >> Same exact regex as above:
> >>
> >> $test =~ s{  (.*?)  [(]   (.*?)   [)]  }
> >>   {$1}xmsg;
[...]
> > Can you tell me what the function of the square-brackets are for regexps?
> > How are they different than regular parens?
>
> '[' and ']' define a character class, but you don't really need a character
> class in your example.


Adam,

just to sum up:

$test =~ s{ (.*?)  \(  (.*?)  \) }
  {$1}xsg;

- "\(" instead of "[(]": more readable
- no /m modifier   : unnecessary without ^/$-anchors
- /s   : may be appropriate for your html source text

:-)

Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: How to display database records in a web page !!!!

2006-03-06 Thread Hans Meier (John Doe)
Madhu Kumar am Montag, 6. März 2006 09.57:
> Hi , 

Hi Madhu Kumar

your problem is not perl, but html related, see below:

> I want to display database records as web page my database 
> contains some entries and which i wanna write as a report in web
> page.
>
> I have written a code for it which fetches the data from database
> which i wil show u below: my requirement is to align each fields and
> dispaly them as a report .
>
> #!/usr/bin/perl -w
> use DBI;
>
> #use CGI qw(:standard);
> #use CGI::Carp qw(fatalsToBrowser carpout);
> print("Content-type: text/html\n\n");
>
>
> my $dbh = open_dbi();
>
> my $sth2 = $dbh->prepare( q{ SELECT * From longdescs } )
>
> or die "Can't execute statement  $DBI::errstr";
>
> $sth2->execute();
> print "\nContent of Database is \n\n";
>
> print " bug_id\t who\t  bug_when\t work_time\t
> thetext\t isprivate\t already_wrapped\n";
>
>
>my( $bug_id, $who, $bug_when, $work_time, $thetext,
> $isprivate, $already_wrapped );
>$sth2->bind_columns( undef, \$bug_id, \$who,
> \$bug_when, \$work_time, \$thetext, \$isprivate, \$already_wrapped
> );
> while( $sth2->fetch() )
> {
> print "$bug_id\t, $who\t, $bug_when\t, $work_time\t $thetext\t
> $isprivate\t $already_wrapped\t \n";
> }
> $sth2->finish();
>  print"\n";
> $dbh->disconnect;
> sub open_dbi
[...]
> 
> when i run this script on apache web server it messes up all data and
> displays like this which doesn't give a clear picture of what is
> what.

One or more consecutive \t, \n, ' ' are taken as one white space when 
*rendering* the web page (with exeption, see below). 
You can see your formatted output (only) in the html *source*.

What you can do:
a) put  and  around your output, so your formatting 
is rendered literally (the easyiest way)
b) use html tables to format your data in columns

There must be at least one modul on search.cpan.org that can display data 
tables as html tables in an easy way.

For all html stuff, http://en.selfhtml.org/ is a good start, it explains all 
in an easy way.

> Content of Database is bug_id who bug_when work_time thetext isprivate
> already_wrapped 6 , 4 , 2006-02-23 10:35:09 , 0.00 Test
> ! 0 0 7 , 6 , 2006-02-23 10:52:50 , 0.00 Test for 0 0
[...]
> i want the code to display records like a clear report with individual
> fileds having spaces in between them, i hav been fighting with the
> code for longtime .

hth,
Hans

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: hash of hashes & arrays

2006-03-04 Thread Hans Meier (John Doe)
regatta am Freitag, 3. März 2006 21.29:
> Good morning/evening everyone,
>
> I have a hash of data , this hash is very big with dynamic elements
> (strings, numbers, hashes, arrays)
>
> Here is an example
>
> $info{'system'}{'load'}{'1'}
> $info{'system'}{'load'}{'5'}
> $info{'system'}{'load'}{'15'}
> $info{'system'}{'hostid'}
> $info{'system'}{'time'}
> $info{'system'}{'hostname'}
> $info{'system'}{'network'}{'eth0'}{'ip'}
> $info{'system'}{'network'}{'eth1'}{'ip'}
> $info{'system'}{'mount'}{'/'} ==> array (/dev/sda1, 100, 10%, 4220)
>
>
> The size and the data may get changed, so is there any  function that
> can help me to print all the %info data  to be like this :
>
> system.load.1
> system.load.2
> ..
> ..
> system.hostname
> system.network.eth0.ip
> ...
> system.mount././dev/sda1
> system.mount./.100
> system.mount./.10%
> 
>
> I can't think about a way to do that

Hi Regatta,

Below is a possible way to do it. I'm sure there are modules on cpan.org 
dealing with the problem of building the path of all leaf nodes of a tree.

You have to adapt the script if you also want the values printed out.

hth,
Hans

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


# any nested data structure of hashes, arrays, scalars
#
my %data=(a=>{bb=>1, cc=>[2,3,4,5]}, b=>5, c=>{x=>6, y=>{v=>7,w=>8}});


# recursive sub to build path
#
sub dotted_notation {
  my ($item, $str)[EMAIL PROTECTED];
  if (my $ref=ref($item)) {
# $item contains nested non-scalar data
#
if ($ref eq 'ARRAY') {
  _recursive($item->[$_], $str.($str ? '.' : '').$_)
for @$item;
}
elsif ($ref eq 'HASH') {
  _recursive($item->{$_}, $str.($str ? '.' : '').$_)
for keys %$item;
}
else { warn "'$ref' not supported";}
  }
  else {
# leaf reached, print out accumulated path
#
print "$str\n";
  }
}

dotted_notation(\%data);

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: problems with logical && (and) statement

2006-03-04 Thread Hans Meier (John Doe)
Angus am Freitag, 3. März 2006 17.40:
> Yes, I did have that typo in my script.  I fixed it but I am still never
> seeing anything print out that says "I have a match" as the first if
> control should do. 

Have you ensured that the compared data structures meet the conditions for a 
match? The comparison may be ok, but the data structures are not as expected.

You could look at that with

use Data::Dumper
Dumper (\%dhcp, \%ipdb);

> It seems the syntax is wrong somehow. 

Code with syntax errors can't be compiled and therefore does not run...

Dont forget to put

use strict;
use warnings;

at the top of your code; may give you hints about "semantic" errors.


hth,
Hans

[snipped]

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: problems parsing a DHCP.leases file.

2006-02-27 Thread Hans Meier (John Doe)
Angus am Montag, 27. Februar 2006 08.25:
> Hi all,
>
>
>
> I am having some problems filling a variable based on the contents of a
> dhcpd.leases file.  All I want at this time is the hostname and ip address.
> My eventual goal is to create hash of hashes with this information but for
> now I just want to read in the file and see that I have defined my
> variables correctly.  I am able to get the IP address but the $hostname
> variable is always undefined.  The syntax for any given host in a leases
> file looks like this:
>
>
>
> lease 10.10.97.207 {
>
>   starts 2 2005/12/20 16:10:51;
>
>   ends 2 2005/12/20 20:10:51;
>
>   tstp 2 2005/12/20 20:10:51;
>
>   binding state free;
>
>   hardware ethernet 00:0b:97:2b:ea:fe;
>
>   uid "\001\000\013\227+\352\376";
>
>   client-hostname "HOST1";
>
> }
>
>
>
> Here is what I have so far.
>
>
>
> #!/usr/bin/perl
>
> #
>
> use strict;
>
> use warnings;
>
>
>
> my $dhcp_data = "dhcpd.leases";
>
>
>
> my %dhcpd;
>
> my $ip;
>
> my $hostname;
>
>
>
> {
>
> open (DHCPD, $dhcp_data) || die "Can't open $dhcp_data $!\n";
>
>
>
> while (my $line = ) {
>
> next if ($line =~ /^\s*$/ or # blank line
>
>  $line =~ /^\s*#/ );
>
>
>
> if ($line =~ /^lease (\d+\.\d+\.\d+\.\d+)/) {
>
> $ip = $1; }
>
> elsif ($line =~ /^client-hostname/) {
>
> $hostname = $1; }
>
> else {next;};
>
> print "I found IP:$ip\n";
>
> print "I found Hostname: $hostname\n";
>
> }
>
> }

Here is a way to process one lease { } 
after another, with the possibility to extract every field you want.

I think it is easy to read, understand, and alter.

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


local $/="}\n"; # < look here!
while (my $record=) {

  #print "*** $record ***"; # for debugging record extracting

  my ($lease)=$record=~/lease\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
  my ($binding_state)=$record=~/^\s+binding\s+state\s+(\w+)/m;
  my ($client_hostname)=$record=~/^\s+client-hostname\s+"([\w.-_]+)"/m;

  print "lease '$lease' (host '$client_hostname') has ".
 "binding state '$binding_state'\n";
}




__DATA__
lease 10.10.97.207 {

  starts 2 2005/12/20 16:10:51;

  ends 2 2005/12/20 20:10:51;

  tstp 2 2005/12/20 20:10:51;

  binding state free;

  hardware ethernet 00:0b:97:2b:ea:fe;

  uid "\001\000\013\227+\352\376";

  client-hostname "HOST1";

}
lease 10.10.97.208 {

  starts 2 2005/12/20 16:10:51;

  ends 2 2005/12/20 20:10:51;

  tstp 2 2005/12/20 20:10:51;

  binding state free;

  hardware ethernet 00:0b:97:2b:ea:fe;

  uid "\001\000\013\227+\352\376";

  client-hostname "HOST2";

}
=

This prints out:

lease '10.10.97.207' (host 'HOST1') has binding state 'free'
lease '10.10.97.208' (host 'HOST2') has binding state 'free'


hth,
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




[rather OT] Re: alternating bgcolor in rows

2006-02-25 Thread Hans Meier (John Doe)
henry chen am Samstag, 25. Februar 2006 07.07:
> I can't seem to figure out how to alternate the bgcolor for each row that
> i'm printing from arrayref.  Is there a 'foreveryother' function that would
> allow me to put two lines in the loop?  Or is there someway I can put two
> rows of information and loop that?  Here's what I have so far.
>
>
>
>
>
> my $rows = $dbhandle->selectall_arrayref($sql) || die $dbhandle->errstr;
>
> if (@$rows) {
>   print " width='70%'>" .
> "TitleDescriptionPriceEmail";
>   foreach my $row (@$rows) {
> print "" . join ("", @$row) . "\n";
>   }
>   print "\n\n";
> }
> else {
>   print "No matches found\n";
> }
>
> Thanks for the help!

Hi!

Beside the answer you got, you could consider using stylesheets to avoid 
hardcoding colors. So, you would not assign two different colors for the even 
and odd rows, but assign one of the two classes 'even' or 'odd', 

  ...

and assign them colors via an external stylesheet. If you chose to change the 
colors later, you do it in one place: in the stylesheet.

This is alreay offtopic-not-perl-related, but to generalize this: 
It will make it *much* easier to maintain the (x)html if you
- always refer to an external stylesheet from every generated page
- assign css-classes to every x(html) element

The latter allows you to locate a specific element within the page by css at 
any later time: You are prepared to do layouting things you don't think of at 
the moment - only in one file.

Again, sorry for being offtopic.

Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: alternating bgcolor in rows

2006-02-25 Thread Hans Meier (John Doe)
Bob Showalter am Samstag, 25. Februar 2006 15.03:
> henry chen wrote:
> > I can't seem to figure out how to alternate the bgcolor for each row
> > that i'm printing from arrayref.  Is there a 'foreveryother' function
> > that would allow me to put two lines in the loop?  Or is there someway I
> > can put two rows of information and loop that?  Here's what I have so
>
> Instead of tracking an odd/even row number, you can initialize two
> colors before the loop:
>
> my ($ca, $cb) = ('red', 'green');   # Christmas-y!
>
> Then inside the loop, always use $ca for the color, and just swap the
> colors after you use them:
>
> while (...blah) {
>
>   print qq[];
>   ($ca, $cb) = ($cb, $ca);
>
> }
>
> HTH

Hi together

The different answers are very interesting, I'd never thought of the last two!

I'd like to add another, which is also usable with more than two colors.
I would very much appreciate improvements, since it's the first time I use 
overload :-)

=
package ColorAlternator; # Cycles through a number of colors

use strict; use warnings;

use overload '""' => \&color;

sub new {
  my $class=shift;
  bless {c=>[EMAIL PROTECTED], i=>0, n=>[EMAIL PROTECTED], $class;
}

sub color {
  my $self=shift;
  my $c=$self->{c}->[$self->{i}];
  $self->{i}=++$self->{i} % $self->{n};
  $c;
}

package main;

my $color=ColorAlternator->new( qw[ #303030 #00 #ee] );

for my $row ( 1..10 ) {
  print "color is $color\n";
}
=

Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: alternating bgcolor in rows

2006-02-24 Thread Hans Meier (John Doe)
Chas Owens am Samstag, 25. Februar 2006 08.18:
[...]
> Aye, I am an idiot.

No, your help on this list is very valuable, and, imho, typos are not proof 
for idiocy...

Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: alternating bgcolor in rows

2006-02-24 Thread Hans Meier (John Doe)
Chas Owens am Samstag, 25. Februar 2006 07.17:
[...]
> Use the module operator (%) with an if statement to do different
> things in a loop:
>
> my $rows = $dbhandle->selectall_arrayref($sql) || die $dbhandle->errstr;
> if (@$rows) {
> print " width='70%'>" .
>
> "TitleDescriptionPriceEmail"; my

> $i = 1;

my $i=0;

> foreach my $row (@$rows) {
> my $color;
> if ($i % 2) { #odd rows

if (++$i % 2) { # odd rows

otherwise you'll get only odd rows :-)

> $color = "#303030";
> } else { #even rows
> $color = "#00";
> }
> print qq() . join ("",
> @$row) . "\n";
> }
> print "\n\n";
> } else {
> print "No matches found\n";
> }

Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: tar command

2006-02-24 Thread Hans Meier (John Doe)
Irfan J Sayed am Freitag, 24. Februar 2006 19.13:
> Hi ,
>
> I already tested with /vobstg.tar in the gzip command but still it's
> hanging and i am executing this perl script from / partition only.
>
> Main thing is that it's creating /vobstg.tar.gz file but not coming to
> shell prompt or not executing next command
>
> plz let me know any other option.
>
> Regards
> Irfan Sayed
[...]

What about using the additional -z option of tar, so you don't have to call 
gzip separatly?

hth
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: tar command

2006-02-24 Thread Hans Meier (John Doe)
Irfan J Sayed am Freitag, 24. Februar 2006 16.36:
> Hi All,
>
> I need to execute unix tar command thru perl file
> can somebody helps me out in this regard

http://search.cpan.org/~kane/Archive-Tar-1.28/lib/Archive/Tar.pm

hth
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: simple references question

2006-02-24 Thread Hans Meier (John Doe)
Bryan R Harris am Donnerstag, 23. Februar 2006 19.30:
> Responding to your references to modules, we haven't used them because we
> can't count on them being there.  Obviously my problem, not yours.  =)
[...]
There is no must to have them installed in default locations. You can install 
them  in any directory as long it is in @INC, and deliver them together with 
your scripts. If the modules are pure perl, just copying is ok.

And then, a lot of standard modules belong to every perl distribution, so they 
are there.

If unsure about there presence, you could distribute a test script...
a) listing all present modules
b) checking if the required ones are present (with eval {use module}; or so)

hth,
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: simple references question

2006-02-23 Thread Hans Meier (John Doe)
Bryan Harris am Donnerstag, 23. Februar 2006 16.41:

Hi Bryan 

It's a bit lengthy, but I hope it motivates you a bit to look around...

> You mention larger projects, and I've heard about "reusable code"...  Is
> that generally done by copy/paste into the script you're working on?

Code copied&pasted around is a candidate for a perl module, the perlish 
variant of libraries. 

> Or is 
> there a way to somehow "compile" like C does where it will gather chunks
> from a library and stuff them together into a single script?  

You stuff the modularized code together by 

use SomeModule;
use AnotherModule;

into different scripts (instead of copy&paste what's in the modules). 

If you detect an error, you can "simply" (means: if no side effects have been 
worked around outside the module...) correct it in the module and don't have 
to "oh shit, into which of my scripts did I copy the error made 3 years 
ago?!?".

Modules should have an as easy, logical, minimal, "problem-covering", 
natural,... API as possible :-)
They hide complex code and make it possible to change the implementation.

Sorting algorithms are a good example to modularized/encapsulate into modules. 
A fake example code snippet:

  use MySortStrategy 'sort'; # line A
  my @sorted=sort(@some_unsorted_data);

If you want to use another sort strategy, you simply change  line A to

  use MyOtherSortStrategy 'sort';

The point here is that the implementation is separated from usage.

Another fake example with another approach:

  use MyGenericSort 'sort';
  my @sorted1=sort(-strategy=>'quicksort', -data=>[EMAIL PROTECTED]);
  my @sorted2=sort(-strategy=>'bubblesort', -data=>[EMAIL PROTECTED]);

> I ask because 
> portability is huge for me, I have to produce single standalone scripts
> that work on any of various unices.

That's a good occasion to abstract the differences between the unices and 
"hide" them behind a common API. An example for that is the module

  File::Spec - portably perform operations on file names.

[...]

Or look at the Storable module:
No need the explicitly code the storing of different data structures to a file 
every time! Just give the arbitrary complex perl data structure to one of the 
subroutines provided and saving is done with one line of code.

The object oriented paradigma allows for again more resusability...

Check the perl documentation

  perldoc perl

Look at the mass of modules on search.cpan.org, and there are certainly lots 
of online resources in english available (which I don't have handy).

hth,
Hans




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Extract multiple lines

2006-02-23 Thread Hans Meier (John Doe)
Hans Meier (John Doe) am Donnerstag, 23. Februar 2006 13.07:
[...]
sorry for replying to myself...
> > The script is only extracting the first line of the heading..
>
> Yes, with every loop trough @lines, you overwrite your variables $title to
> $dewey.

this doesn't matter since you print the contents out before overwriting.

Should get some sleep

Greetings
Hans

-- 
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 multiple lines

2006-02-23 Thread Hans Meier (John Doe)
Jack Daniels (Butch) am Donnerstag, 23. Februar 2006 10.30:
> It's driving me bonkers and can't afford any more psychiatic bills. The
> data is a saved .txt file when viewing from a website. The vendor will not
> give us an actual file even though we payed a montly fee for use of the
> database. I have around 5000 records that need to be converted to MARC
> cataloging records. I need to either have the data from each heading on 1
> line or have the script extract each heading and all the subsequent lines.
>
> The script is only extracting the first line of the heading.. 

Yes, with every loop trough @lines, you overwrite your variables $title to 
$dewey.

> I can only 
> have 1 blank line between each record which works in the script. If I right
> click then import to excel when viewing the records at the website, each
> heading is a continous string, which is what I need. I can then save as a
> tab delimited file and the lines for each heading remian continuous, which
> works. But we have ceased our subscription and I now only have saved .txt
> files of the 5000 records.   I can't figure out how and where to modify the
> script to work on the files. I suppose I could spend a couple months
> manually joining lines, but that really cuts into naptime.

I don't know what MARC cataloging records are nor is my english enough good to 
understand what you exactly mean, and I don't know if the leading spaces on 
every line below are in the sample data, but It may help you to produce a CSV 
file from the data.

So, you can adjust my script below or wait for undoubtly arriving better 
solutions:

[...]

> HERE IS THE SCRIPT
>
> open(MYINPUTFILE, "<1000chomp.txt"); # open for input
>
> my(@lines) = ; # read file into list
>
>
> my $title;
> my $series;
> my $subjects;
> my $physical;
> my $synopsis;
> my $producer;
> my $copyrighted;
> my $dewey;
> for my $line (@lines)
> {
>
> $line =~ /Title/ and $title = $line;
>$line =~ /Title/ and print "=LDR  0nam  220Ia 45e0\n","=245
> 00\$a",$line;
>
> $line =~ /Dewey/ and $dewey = $line;
>$line =~ /Dewey/ and print "=082  \$a",$line;
>
> $line =~ /Producer/ and $producer = $line;
>$line =~ /Producer/ and print "=040  \$aCaSRRI\n","=260
> \$a",$line;
>
> $line =~ /Copyrighted/ and $copyrighted = $line;
>$line =~ /Copyrighted/ and print "=261  \$c",$line;
>
> $line =~ /Physical/ and $physical = $line;
>$line =~ /Physical/ and print "=300  \$a1 videocassette ( min.)
>
> :\$bsd., col. ;\$c13 mm.",$line;
>
> $line =~ /Series/ and $series = $line;
>$line =~ /Series/ and print "=440  0\\\$a",$line;
>
> $line =~ /Synopsis/ and $synopsis = $line;
>$line =~ /Synopsis/ and print "=520  \$a",$line;
>
> $line =~ /Subjects/ and $subjects = $line;
>$line =~ /Subjects/ and print "=550  \$a",$line,"\n";


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


local $/=""; # split data at 1..n empty lines

# btw: Series does not occur in the sample data
my 
$stops=qr/(?:Title)|(?:Physical)|(?:Copyrighted)|(?:Producer)|(?:Dewey)|(?:Synopsis)|(?:Subjects)|(?:Series)/;

for my $record () {

  my @pairs=split (/($stops)/, $record);
  shift @pairs; # remove the undef 1st entry

  my [EMAIL PROTECTED];

  $keyed{$_}=~s/\s+/ /gs for keys %keyed;

  # now you have one record as key/one-line-value pairs
  # for further processing, see:

  print join "\n", map {"$_=>$keyed{$_}"} keys %keyed;
  print "\n\n";

  # you could sort it, produce a CSV-file, ...
}


__DATA__
  Title 10 fastest growing careers: jobs for the future part four
business
  and computer technology (03616)
  Physical Color; Sound; 15 minutes
  Copyrighted 1990
  Producer GUIDANCE ASSOCIATES (GUID)
  Dewey 371.425
  Synopsis Contents: The business community depends on up-to-the minute
  technology - technology that is changing rapidly. As a result, careers
in
  technology, especially computers and specialized areas such as
accounting
  are much in demand. Takes a look at three business and computer
careers:
  software engineering, computer programming and accounting.
  Subjects CAREER GUIDANCE; CAREER SERVICES
  Holdings
 1/2 VHS video: Head Office, 1 copy



  Title 10 fastest growing careers: jobs for the future part one legal
and
  health (03613)
  Physical Color; Sound; 15 minutes
  Copyrighted 1990
  Producer GUIDANCE ASSOCIATES (GUID)
  Dewey 371.425
  Synopsis Contents: Takes a look at the fast growing health and legal
  fields. Talks to a registered nurse about her changing role in a major
  hospital, a physician's assistant who works with two doctors in a busy
  family practice, and a paralegal who works with an attorney.
  Subjects CAREER GUIDANCE; CAREER SERVICES
  Holdings
 1/2 VHS video: Head Office, 1 copy
=

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For add

Re: simple references question

2006-02-22 Thread Hans Meier (John Doe)
Bryan Harris am Donnerstag, 23. Februar 2006 03.46:
> Thanks!
>
> Regarding your "note", out of curiosity, how will it help a lot in the end?
> I've been scripting for almost 5 years now, and have produced >100 scripts
> that are used in data analysis work by ~15 people, and have never used "use
> strict", nor declared any variables with "my".  Everybody says it's good
> coding practice, but I haven't yet figured out why...  Just wondering.
>
> Thanks again for your response.
>
> - Bryan
[...]
> > NOTE:  Always use strict and warnings.  It's much better to start now
> > than to have to change your habits later.  It's like learning to type;
> > at first it makes things slower, but in the end it will help a lot.
[...]

Hi Bryan

Sorry for stepping in (and my english - no offence intended)... 
Timothy's note is really good advice. Everybody on this list will give it. 
There must be a reason for that...

Of course one can use a keyboard with two fingers during years; but it's 
simpler using all ten :-)

Expecially 'use strict' provides some sort of "automated error detection" and 
thus more formal means to produce correct code; this is better than a 
more error prone "it seems to be correct"-like assumption.

When you code more than "little" scripts, when you create modules with 
reusable code in a bigger software project, it makes overview and maintenance 
*much* easier.

Just one example: When you declare your variables, you see at the first glance 
where it is declared, and if you see the variable somewhere without 'my', you 
know that it already has been (or should have been - if not, an error is 
produced) declared. 
Without 'my', you can't know that, but have to look into the whole code to 
find out if you are just declaring it at the position or using it: Your 
perspective, then, is less locally than possible.

Since you ask a question like that one in your original post after 5 years of 
scripting: Take his advice! 

Greetings
Hans


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Why does my inheritance hierarchy get screwed up?

2006-02-22 Thread Hans Meier (John Doe)
Johannes Ernst am Donnerstag, 23. Februar 2006 00.19:
> [Blogged about it here: http://netmesh.info/jernst/Technical/perl-
> inheritance-problem.html ]
>
> There are three very simple classes in the following code: C is a
> subclass of B, which is a subclass of A.
>
> If I try to instantiate B (see last two lines of the code below), I'm
> getting this output:
>
>  Point B: Exporter
>  Can't locate object method "new" via package "B" at madness.pl
> line 23.
>
> However, if I comment out class C (which isn't even instantiated by
> my code!) it works!
>
> It also works if I rename class B to Z, for example. And where in the
> world would class Exporter suddenly come from? (see debugging output
> of the @ISA)
[...]

B is a core compiler module... this also explains where the Exporter in @ISA 
is coming from, since B 'isa' Exporter.

It seems that - see to the order of paths in your @INC - the core B is loaded 
and not your B.

Sorry, I did not delve deeper in your code.

hth
Hans 

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: A problem with apache installation http://localhost issue

2006-02-22 Thread Hans Meier (John Doe)
zhou jian am Mittwoch, 22. Februar 2006 22.40:
> Hello perl fellows:

Hi Paul

This is the wrong list for this question (see your subject) but:

> I encountered a problem when I was installing a perl
> module. The httpd server related module was hanging
> overnight when it was trying to test
> http://localhost:X...
>
> Today, I tested with my httpd server installation.
> I found that I can view the webpage after I started
> httpd server through the actually ip address. I have
> configured my ip address under /etc/hosts.

Check that the entry

127.0.0.1 localhost 

is present.

> However, I couldn't view the webpage through
> http://127.0.0.0/ or http://localhost/
>
> It looks bizzare to me, if I can't view it through
> http://localhost, then I couldn't install the httpd
> related perlmodules because they require the testing.


Apache only listens on IPs and Ports that are configured in the httpd.conf.
Yours seems not to be configured to listen on 127.0.0.1, you can check that by

$ netstat -neatp

Depending on your apache configuration, a

Listen 127.0.0.1:80

in the httpd.conf may be sufficient.

hth,
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Type globs of subroutines?

2006-02-22 Thread Hans Meier (John Doe)
Angerstein am Mittwoch, 22. Februar 2006 11.05:
> Short Question:
>
> Is type globbing of subroutines possible or not?

yes,

perl -le 'use warnings; use strict; \
sub sub1{1}; \
*sub2=\&sub1; \
warn sub2(); \
'
> for something like &supersub(\&smallsub);

This (passing a subroutine reference as argument to a subroutine):
is unrelated to the above.

perl -le 'use warnings; use strict; \
sub sub1{shift->()}; \
sub sub2 {2}; \
warn sub1(\&sub2);
'

hth
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Repeated Regex over a line with double quotes

2006-02-21 Thread Hans Meier (John Doe)
Wagner, David --- Senior Programmer Analyst --- WGO am Dienstag, 21. Februar 
2006 23.55:
>   here is a small snippet of code(LABEL1) which appears to remove a comma
> which lies between two double quotes. I run it and and display output and
> the one line of code which does have the comma is cleaned up. In LABEL2 ,
> is a snippet of code which does not work, but in all appearances is the
> same as my small snippet of code. The working code is AS 5.8.3 on Windows
> XP while the the failing is on Sun and is also 5.8.3.
>
>   I am receiving some data and and need to clean up and also split. I 
> prefer
> to not have to load any type of csv handler and works for the most part.
>
>   I don't see the difference in the code other than two different systems.
>   Note: Moved this same code over ( didn't occur to try it, but head must 
> be
> stuck). It runs and removes the , from within the double quotes.
>
>   Has to be something simple that I am missing. Though been doing Perl for
> quite a while, never really been good at the regex processing.
>
>   Thanks.
>
> Wags ;)
> ===
>==
>
> LABEL1:
> #!perl
> use strict;
> use warnings;
>
> my $MyIn  = 0;
> my $MyOut = 0;
>
> my $MyHldData;
> my $MyWrkFld;
> my $MyWrkFldUpd;
>
> while (  ) {
> chomp;
> s/\r//g;
> next if ( /^\s*$/ );
> my $MyHldData = $_;
>
> if ( /"/ ) {
> printf "*1a* Looking at line with quotes\n";
> while ( /("[^"]+")/ ) {
> $MyWrkFld = $1;
> printf "*1*  <%s>",
> $1;
>
> $MyWrkFldUpd = $MyWrkFld;
>
> if ( $MyWrkFld =~ /,/ ) {
> printf "<--Comma hit!!";
> $MyWrkFldUpd =~ s/[,"]//g;
> s/$MyWrkFld/$MyWrkFldUpd/g;
>  }
>  else {
> $MyWrkFldUpd =~ s/"//g;
> s/$MyWrkFld/$MyWrkFldUpd/g;
>  }
> printf "\n";
>  }
>  }
>  else {
> printf "No quotes in line %d\n",
> $.;
> next;
>  }
> printf "ln:<%5d>\nor:<%s>\nmd:<%s>\n",
> $.,
> $MyHldData,
> $_
>  }
> __DATA__
> 2006-02-18 12:00EE,"TBUTHGHN - GGTT","TEN DIGGB","TEN DIGGB","FHEZGG PEINT
> TD","7077 CBNTBLIDETGD GEY",2006-02-14
> 12:00EE,15,"10:05","0152785","2737526",1,1250,10,"892913494",1,25
> 2006-02-18 12:00EE,"TBUTHGHN - GGTT","TEN DIGGB","TEN DIGGB","EETGH
> EGCHENICEL","7840 BELBBE EVG",2006-02-15
> 12:00EE,16,"11:27","0107405","2846954",1,1167,3,"916708540",1,25 2006-02-18
> 12:00EE,"TBUTHGHN - GGTT","TEN DIGGB","TEN DIGGB","EETGH EGCHENICEL","7840
> BELBBE EVG",2006-02-15
> 12:00EE,17,"13:47","0107405","2846954",1,456,1,"916708557",1,25 2006-02-18
> 12:00EE,"TBUTHGHN - GGTT","TEN DIGGB","TEN DIGGB","NEVEL DGPBT LGVGL HGPEIH
> EGGNT","N46433 FLGGT TT, BLDG 661-3",2006-02-16
> 12:00EE,18,"11:40","0164109","2500058",1,529,1,"1078754644",1,25
>
> ==
>
> LABEL2:
>   
>
> INPUTTP: while () {
> chomp;
>
> $in++;
> s/\r//g;
>
> next if ( /^\s*$/ );# bypass blank lines
>
> if ( ! /,(\d+)$/ ) {
> printf "Expecting a csv line ending with the total number of
> times associated with\n"; printf "a terminal, but did not get a hit!\n";
> printf "Data(%d):\<%-s>\n",
> $.,
> $_;
> diet(5, $MyFileIn);
>  }
>
> $MyDtlCnt = $1;
> undef @MyWorka;
> undef @MyUnSortedData;
>
> if ( /"/ ) {
> printf "*1a* Looking at line with quotes\n";
> while ( /("[^"]+")/ ) {
> $MyWrkFld = $1;
> $MyWrkFldUpd = $MyWrkFld;
> if ( $MyWrkFld =~ /,/ ) {
> $MyWrkFldUpd =~ s/[,"]//g;
> s/$MyWrkFld/$MyWrkFldUpd/g;
>  }
>  else {
> $MyWrkFldUpd =~ s/"//g;
> s/$MyWrkFld/$MyWrkFldUpd/g;
>  }
>  }
>  }
>
>   .

For fun I played around a bit with regexes, but I think the usage of a csv 
module is easier :-)

while () {
chomp;

# extract fields
#
my 
@fields=$_=~/((?:".*?")|(?:(?<=,).*?(?=,))|(?:(?<=,).*?$)|(?:^.*?(?=,)))/g;

# remove quotes
#
$_=~s/"(.*?)"/$1/ for @fields;


# print the fields separated with *
#
print join '*', @fields; print "\n";
}

__DATA__
2006-02-18 12:00EE,"TBUTHGHN - GGTT","TEN DIGGB","TEN DIGGB","FHEZGG PEINT 
TD","7077 CBNTBLIDETGD GEY",2006-02-14 
12:00EE,15,"10:05","0152785","2737526",1,1250,10,"892913494",1,25
2006-02-18 

Re: Net::Server

2006-02-19 Thread Hans Meier (John Doe)
Tom Allison am Samstag, 18. Februar 2006 21.27:
> I am trying to set up a server using Net::Server.
> Mostly this is out of curiousity more than anything else.
> But following the man pages I got stuck.
>
> I was trying to set up a server to connect to port 8081,
> but none of the configuration options I've put in below appear in the file
> I'm running.

Ok, since nobody else answered... I didn't have a thorough look at the module. 
Maybe my ideas help, but I doubt it a bit:


What about

package  Net::Server::AuthServer;

?

> use strict;
> use warnings;
> use Net::Server;
> use Data::Dumper;
> use vars [EMAIL PROTECTED];
> @ISA = qw[Net::Server];
>
> my $server = bless {
>port=> '8081',
>log_level   => '4',
>reverse_lookups => '1',
>pid_file=> '/var/run/net_test.pid',
>listen  => '16',
>user=> 'nobody',
>group   => 'nobody',
> }, 'AuthServer';

}, 'Net::Server::AuthServer';

?

> print Dumper($server);
>
> $server->run();
>
> ##
>
> The output shows up as:
>
> [EMAIL PROTECTED]:~$ perl -w -T net_test.pl
> $VAR1 = bless( {
>   'group' => 'nobody',
>   'pid_file' => '/var/run/net_test.pid',
>   'listen' => '16',
>   'log_level' => '4',
>   'reverse_lookups' => '1',
>   'user' => 'nobody',
>   'port' => '8081'
> }, 'AuthServer' );

This is ok, since you dump from the actual namespace a variable defined in the 
same namespace.


Did you have a look into the source code of the provided subclasses of 
Net::Server (Net::Server::PreforkSimple etc.).
This may help.

hth,
Hans

> 2006/02/18-15:22:15 AuthServer (type Net::Server) starting! pid(5506)
> Port Not Defined.  Defaulting to '20203'
> Binding to TCP port 20203 on host *
> Group Not Defined.  Defaulting to EGID '1000 1000 44 40 29 25 24 20'
> User Not Defined.  Defaulting to EUID '1000'
>
> #
>
> It's pretty clear that it's not really taking any queues from me.
> I'm just taking my queues from the man pages.
> Should I take my queues from someplace else?

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




[OT] Re: perl with databases

2006-02-19 Thread Hans Meier (John Doe)
Owen Cook am Sonntag, 19. Februar 2006 22.21:
> I suggest you use Matt Sergeant's DBD::SQLite a Self Contained RDBMS in a
> DBI Driver.
>
> It rocks

Owen, thanks a lot for this tip!!!
The aggregate function feature looks very promising
:-)

Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Error in the "if" block

2006-02-19 Thread Hans Meier (John Doe)
Ron Smith am Sonntag, 19. Februar 2006 21.27:
> I changed this too. Thanks, Hans!
>
> > [irrelevant parts snipped away]

The "irrelevant" was not quite true...

As always, John W. Krahn looked closer into the code, finds simpler solutions 
and does not miss to point to the appropriate documentation - if in doubt, 
take his advice :-)

Greetings
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Error in the "if" block

2006-02-19 Thread Hans Meier (John Doe)
Ron Smith am Sonntag, 19. Februar 2006 18.47:
> Hi all,

Hi Ron

>   This page accepts a series of numbers, separated by spaces, and gives the
> values listed bellow.
>   I'm getting the following error, 

No information about the input that causes the error; are there also inputs 
not causing an error?

>   but don't see why. Can anyone spot my error?
>   Please, enter numbers separated by spaces only!: Bad file descriptor at
> E:/www/cgi-bin/pg93ex3.11SeriesOfNumbers.pl line 14.

Hm, line 14 contains the die "Please..."

>
> I've narrowed the problem down to the "if" block (the regex), I'd like to
> accept numbers and spaces only. Here's the code:
>
> #!E:/www/perl/bin/perl.exe
>
> use strict;
> use warnings;
> use CGI qw( :standard );
> use CGI::Carp qw( fatalsToBrowser );
>  print header();
>
>  my $userIn = param( "textfield" );
>
> if ( $userIn =~ /^(\d+|\s*)$/ ) {

This does not match inputs containing more than one number.

What you want is something like

/^\s*((?:\d+\s*?)+)\s*$/

The inner (?:) does not capture output (see perldoc perlre), 
and the regex trims the input (which is allowed to contain leading and 
trailing space)

>  $userIn = $1;
> } else {
>  die "Please, enter numbers separated by spaces only!: $!";
> }

The if-else could be shortened to (untested, so please check):

die "Bla" unless ($userIn)=$userIn=~/^\s*((?:\d+\s*?)+)\s*$/;

> my @numbers = split( / /, $userIn );

This only splits on a single space character.

my @numbers = split /\s+/, $userIn;

splits (explicitly) on the same whitespace allowed in the regex above.



hth!
Hans

[irrelevant parts snipped away]



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: populating a Hash

2006-02-18 Thread Hans Meier (John Doe)
David Gilden am Samstag, 18. Februar 2006 16.29:
> Good morning,

Good evening here ;-)

> I would like to populate a hash from a csv text file, then test for the
> existence  of a value in the hash. If not found return an error message and
> exit.
> ithe text file will have the format of:
> # whitelist created 2/18/06 or some other comment on the first line
> name1,nick1
> ---
> name25,nick25
> ---

I suppose the '---'s are not part of the file?


Don't forget:

use strict;
use warnings;

> my $approvedUser = pram('approvedUser'); # cgi.pm
>
> my $whitelist = './'whitelist.txt;

This line leeds to a syntax error, look at/after the second single quote.

> my %hash

my %hash;

> open(EL,"$whitelist") ||  &errorMessage( "Read in, Could not find
> $whitelist, $!"); 

No need to double quote $whitelist in the first line.

You use an error sub to write an error out and to exit with an *ok* exit 
status. although the script won't do what it shold. The better way would be 
to die:

open (EL, '<', $whitelist) or die "Read in, Could not find $whitelist, $!";

> my @lines = ; 
> close(EL);

close EL or die $!;

> foreach(@lines){
> next if /#/;

This skips also lines with a '#' not at the beginning.

next if /\s*#/;

> my($key,$val)= split (@lines,",");

You are within a loop processing a single line of @lines (which is hold in 
$_), and did not read perldoc -f split:

my($key,$val)= split ',', $_;

>$hash{$key} = $val;
>  }
> close(EL);

EL is alredy closed.

> if (!defined $approvedUser =~ %hash){
> &errorMessage( "your not an authorized user")
> }

print "your not an authorized user"
   unless exists $hash{$approvedUser};

This is a simple test for existence of a key in a hash. See 
perldoc -f exists

> errorMessage(message){
> shift;
> print "$_\n";
> exit;
> }

No need for that anymore.

> How close am I to having a working script, I have guessed at some of syntax
> here, and am not familiar with using 'defined'.

use strict will reveal syntax guesses.


BTW, there is also a short way to get the data into %hash. Before just using 
it, please read the man pages for map and grep.
(The usage of __DATA__ and  is a handy way to simulate file input).

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

my %hash=map {split ',', $_} grep {$_!~/\s*#/} ();

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

__DATA__
# a comment
name1,nick1
name25,nick25
===


hth,
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Process large file with hash

2006-02-18 Thread Hans Meier (John Doe)
Andrej Kastrin am Samstag, 18. Februar 2006 14.08:
> Dear Perl users,
>
> I try to parse 20.000.000 records file but... To solve my recent Perl
> problem I collect my previous posts on this list.
>
> I have bar separated file (FILE_A):
> name1|10
> name2|20
> name3|5
> name4|30
> etc.
>
> I processed it with the following code:
>
> my %scores;
> while (  ) {
> chomp;
> my ($name, $score) = split /\|/;
> $scores{$name} = $score;
> }
>
> Then I have another file (FILE_B) which looks like:
> 
> ID - 001
> NA - name1
> NA - name2
>
> ID - 002
> NA - name2
> NA - name4
>
> etc.
> 
>
> The code below reads each record from FILE_B (ID and NA fields) and sums
> corresponding  NA values from FILE_A:
>
> my ( $ID, %ids );
> while (  ) {
> if ( /^ID\s*-\s*(.+)/ ) {
> $ID = $1;
>}
>elseif ( /^NA\s*-\s*(.+)/ ) {
>   $ids{ $ID } += $scores{ $1 };
>}
> }
>
> for my $id ( keys %ids ) {
> print "$id | $ids{$id}\n";
> }
>
> So we obtain:
> 001|30  #ID is 001 and 10+20=30
> 002|50  #ID is 002 and 20+30=50
>
> The script works perfect, but when I try to process larger files (eg.
> with 20 milions records!), it hangs. 

This is probably due to insufficient RAM, there are 2 hashes with 20 Mio. 
entries to keep in memory... (swapping? Did you see a lot of hard disk 
activity?)

> How should I modify this script 
> that I could process each record from FILE_B separately.

I did not think thoroughly about your particular example, but I think from a 
certain amount of data on to be processed - or if it's foreseeable that the 
amount of data is growing much - a database solution is more appropriate.

The solution (if you have to stick with text input) could include:
- transform input files into a format suitable to import into the db
- import
- create result table
- write result table data out into file

You could use one of the modules in the DBI group.

Or, redesign your application which produces the input text files to write 
directly to a database.

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: property definition

2006-02-17 Thread Hans Meier (John Doe)
Kenneth Moeng am Freitag, 17. Februar 2006 07.21:
> Hello there, I have a problem with property definition of this code,
> please have a look.
>
> #!/usr/bin/perl -w

Hello,

What is the property definition in your code and what problems do you have 
with it?

Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: :: and ->

2006-02-17 Thread Hans Meier (John Doe)
Ken Perl am Freitag, 17. Februar 2006 02.34:
> what is the difference of :: and -> in this statements?
>
> $authInstance =
> Operation::Auth::getInstance($session,$u->authMethod,$u->userId)
>
> $authInstance =
> Operation::Auth->getInstance($session,$u->authMethod,$u->userId)

The first '::' is part of a package name, the package is

package Operation::Auth

The last '::' (in the first example) denotes a sub in this package and is a 
procedure invocation, the sub getting only the passed arguments.

The '->' is a method invocation, and the class name ('Operation::Auth' in this 
case) is implicitly passed to getInstance as first argument (as Chas already 
said).

The two notations are not interchangeable if the sub definition is for example

sub getInstance {
my ($class, $session, $meth, $uid)[EMAIL PROTECTED];
...
}

intended to be called as method.

The first invocation would leed to an error since the first argument 
getInstance receives is $session, and not a class name.


hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: [RESOLVED (workaround?)] Re: Strange "Can't locate Module.pm in @INC" error after chaning from 'use lib' to PERL5LIB

2006-02-15 Thread Hans Meier (John Doe)
Tom Phoenix am Mittwoch, 15. Februar 2006 01.59:
> On 2/14/06, Hans Meier (John Doe) <[EMAIL PROTECTED]> wrote:
> > I'm fine with that, but still don't understand how a path present in @INC
> > is ignored.
>
> It sure looks like it's in @INC, from the message. (You may know that
> PERL5LIB is sometimes ignored for security reasons, but it's not
> ignored if it's in the message.)

Thanks a lot for your answer, Tom, very appreciated!

I must admit that my example was oversimplified: I tried to include 3 paths.

Any form (no, '-, "-quoting, space-, :- ;-separators) of PerlSetEnv in the 
httpd.conf was ignored,...

> Could there be a hidden (control or 
> whitespace) character or something else in there? See whether you can
> compare the @INC that works with the one that doesn't, because that
> sounds like the culprit. Good luck!

...and the solution is

export PERL5LIB=/opt/osf/lib:/opt/smf/lib:/opt/my_perl/lib
(not, single or double quoted)

in the environment. I think i missed the :-variant when I tried first. How 
stupid :-(

Thanks again for driving me to the solution!

Hans

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




Re: Stopping a Service with cgi

2006-02-14 Thread Hans Meier (John Doe)
nishanth ev am Dienstag, 14. Februar 2006 17.56:
> hello Friends,
>
> Have anyone tried stopping a service say httpd usng a
> cgi script ?
> I have set a setuid for the cgi script and the script
> is in the root cgi-bin directory namely
> /var/www/cgi-bin/ with ownership root and have the
> following contents in the file
>
> #!/usr/bin/perl
> $ENV{'PATH'} = '/bin:/usr/bin';
> print"Content-type:text/html\n\n";
> `/etc/rc.d/init.d/httpd stop`;
>
> ./file-name.cgi will stop the httpd but i want to stop
> the httpd when i access this cgi through the browser.

As Tom alredy pointed out, there are some security implications by enabling 
service starting and stopping through a web interface. 

In my persopnal opinion, it's better not to call a (set-id) program but just 
touch or modify a file if possible.

You could set up a cron job to test modification time of the touched file and 
stopping/restarting the service accordingly 
(and, e.g., let it send a notification mail to you or any other recipient not 
provided by the webinterface user).

In any case, be careful not to enable DOS-attacks.

hth,
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: regexpressions help

2006-02-14 Thread Hans Meier (John Doe)
Hans Meier (John Doe) am Dienstag, 14. Februar 2006 21.35:

> if (/^\s*([A-Z][a-z])+\s*([A-Z][a-z])+\s*$/) {
>   # input is ok, so now we format:
>   my $formatted="$1 $2";
>   do_something_with($formatted);
> }

Sorry, this is completely bullshit, shuld have tested before hitting send.



my $userinput="   Hans \n  Meier ";

if ($userinput=~/^\s*([A-Z][a-z]+)\s+([A-Z][a-z]+)\s*$/) {
  # input is ok, so now we format:
  my $formatted="$1 $2";
  print $formatted;
}
print $userinput;

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




Re: regexpressions help

2006-02-14 Thread Hans Meier (John Doe)
Gerald Wheeler am Dienstag, 14. Februar 2006 21.03:
> I am trying to allow input of a person's first and last name in one form
> field, nothing more, nothing less
>
> There should be only one uppercase A-Z character followed by one or
> more lowercase a-z characters followed by one space followed by one
> uppercase A-Z character followed by one or more lowercase a-z
> characters, nothing more.
>
> have tried this which does not work:  /^[A-Z a-z]\s+[A-Z a-z]{1,15}$/

It's not enough restrictive. According to your exact description, it should be 
(untested):

/^[A-Z][a-z]+ [A-Z][a-z]+$/

Of course, you can replace the '+' by {min,max}.

Further, for userfriendliness, you could allow other whitespace, and more 
between the words, and additonally around them, and trim them away 
*afterwards*:

my $userinput=get_from_request();

if (/^\s*([A-Z][a-z])+\s*([A-Z][a-z])+\s*$/) { 
  # input is ok, so now we format:
  my $formatted="$1 $2";
  do_something_with($formatted);
}

hth,
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




[RESOLVED (workaround?)] Re: Strange "Can't locate Module.pm in @INC" error after chaning from 'use lib' to PERL5LIB

2006-02-14 Thread Hans Meier (John Doe)
Hans Meier (John Doe) am Dienstag, 14. Februar 2006 19.08:

> It's very strange:
>
> My apache doesn't start with
>
> [error] Can't locate SMF/Config.pm in @INC (@INC contains: /opt/smf/lib
> [...]) at /opt/smf/apconf/backend/httpd_startup_smf.pl line 228.
>
> But why? The file is there:
>
> # ls /opt/smf/lib/SMF/Config.pm
> /opt/smf/lib/SMF/Config.pm
>
> and the path is obviously in @INC.
>
> The error appears after replacing  use lib '/opt/smf/lib';
> in the httpd_startup.pl with  PERL5LIB="/opt/smf/lib"
> in the init.d script. Before, everything went well, and I changed nothing
> else.
[...]

Ok, finally a 


   use lib qw(/opt/smf/lib);


in the httpd.conf did the trick, while a PerlSetEnv PERL5LIB also didn't.

I'm fine with that, but still don't understand how a path present in @INC is 
ignored.

Hans

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




Strange "Can't locate Module.pm in @INC" error after chaning from 'use lib' to PERL5LIB

2006-02-14 Thread Hans Meier (John Doe)
Dear list

It's very strange:

My apache doesn't start with

[error] Can't locate SMF/Config.pm in @INC (@INC contains: /opt/smf/lib [...]) 
at /opt/smf/apconf/backend/httpd_startup_smf.pl line 228.

But why? The file is there:

# ls /opt/smf/lib/SMF/Config.pm
/opt/smf/lib/SMF/Config.pm

and the path is obviously in @INC. 

The error appears after replacing  use lib '/opt/smf/lib';
in the httpd_startup.pl with  PERL5LIB="/opt/smf/lib"
in the init.d script. Before, everything went well, and I changed nothing 
else. 

I checked permissions, copied&pasted around to avoid typos, tried to find 
someting with strace, etc., but to no avail.

Could anybody please give me a hint what could be the reason? It must be 
something very stupid, but I can't see it. 


Thanks a lot!

Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: BerkeleyDB

2006-02-13 Thread Hans Meier (John Doe)
Tom Allison am Dienstag, 14. Februar 2006 02.28:
> I was trying out some jobs with the Berkeley DB and decided to move up from
> DB_File to BerkeleyDB.  I don't need a lot of features, just speed.
>
> But I keep running into a "dumb" error that doesn't make any sense to me.
> untie attempted while 1 inner references still exist at ./dbm_test.pl line
> 31.
>
> According to docs and the old DB_File method...  I shouldn't get this
> warning. I can't find anything that's not working with the code, but I
> don't like errors just the same...
>
> Any ideas?
>
> #!/usr/bin/perl
>
> use strict;
> use warnings;
> use BerkeleyDB;
> use Digest::MD5 qw[md5_hex];
> use Time::HiRes qw[tv_interval gettimeofday];
> use Data::Dumper;
>
> my %hash;
> my $db = tie %hash, "BerkeleyDB::Hash",
>-Filename => 'authentication.db',
>-Flags=> DB_CREATE
>or die "yer fucked!\n";
>
> for(my $x = 0; $x<10_000; $x++) {
>my $y = int(1 + rand(10_000_000));
>my $t = [gettimeofday];
>if(exists $hash{$y}) {
>  my $value = $hash{$y};
>  print "get ";
>} else {
>  my $value = md5_hex(@$t);
>  $hash{$y} = $value;
>  print "put ";
>}
>print tv_interval($t, [gettimeofday]),"\n";
> }
>
> untie %hash;

The one inner reference mentioned in the error is hold in $db :-)

What you can do:

a) Since you don't use $dh, just say

tie %hash, "BerkeleyDB::Hash";

you can always

my $db=tied(%hash);

b) put before untie %hash a

undef $db;

hth,
Hans

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: single step - debug mode

2006-02-13 Thread Hans Meier (John Doe)
Stephen Mayer am Montag, 13. Februar 2006 17.25:
> Bruce,
>
>   What you want to use is `perl -d file.pl `

...and especially the manuals provided with every perl installation, which is 
a very valuable source for information.

Some tips:

$ perldoc perl # lists manuals.

# search if a manual exists for debugging:
$ perldoc perl | grep deb
   [ -cw ] [ -d[:debugger] ] [ -D[number/list] ]
   perldebtut  Perl debugging tutorial
   perldebug   Perl debugging
   perldebguts Perl debugging guts and tips
   o   enhanced debugger and interactive Perl environment, with integrated
   Described in perldebtut, perldebug and perldebguts.

# help to builtin functions:
perldoc -f FUNCTION

# extracting the POD of a file:
perldoc /path/to/module.pm

# lookup the FAQ
perldoc -q SEARCHTERM


hth
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: substitution

2006-02-13 Thread Hans Meier (John Doe)
Bowen, Bruce am Sonntag, 12. Februar 2006 22.31:
> I have a text string = "^0176  ^0176"
>
> I have set $a = "^0176  ^0176";
> I have set $b = "^0176  ";
>
> I'm using text =~ s/$a/$b/g;
>
> And the text string doesn't change.  I expected it to come out as "^0176  "
> after the substitution.  What is wrong with my logic?

Not shure if it's clear now after Tom's and Michael's posts.

Compared to the '\^'-solution, Tom's advice is generic (meaning that you have 
not to know which meta characters - there are more than the caret - are in $a 
and dont have to handle them explicitly). It's also more readable.

So it's the preferred way to do it.

perldoc perlre

explains all in full detail.

===
#!/usr/bin/perl
use strict;   # don't forget
use warnings; # those two

my $a='^0176  ^0176'; # note the
my $b='^0176  ';  # single quotes
my $text='some text ^0176  ^0176 here ^0176  ^0176 and there';

(my $temp=$text)=~s/\Q$a\E/$b/gs;
print "a) $temp\n";

my $a1=quotemeta($a);
(my $temp=$text)=~s/$a1/$b/gs;
print "b) $temp\n";
===

Hope $text does not contain votes ;-)

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Checking a list for a value

2006-02-11 Thread John Doe
David Gilden am Samstag, 11. Februar 2006 21.54:
> I would like to loop through 'all' acceptable values in an array (my white
> list) then assign a pass or fail value.
>
> In the following code does not accomplish this, it needs to go through the
> entire list before assigning a value.
>
>
> #!/usr/bin/perl
>
> $valToTest = "ac";
>
> @myGoodList = ("10_rater","36_600","ac","cr914","ec12","fairwind");
> $testOk = -1;
>
> foreach my $cat  (@myGoodList){
> if ($cat =~ /$valToTest/) {
> $testOk = 1;
> next;
> } else {
> $testOk = -1;
> # value not in list
> last;
> }
> }
>
> print "$testOk\n";
>
>
> I am going to guess that the foreach is not the right way to address this
> problem.

I think your quess is ok - IF you test for equalty, not matching.

Just use a hash; then you don't have to inspect every value, but can just test 
for existence. Something like

#!/usr/bin/perl
use strict;   # don't forget
use warnings; # those two

my $testval='ac'; # no need for double quotes

my %good=map {$_=>1}
 qw/10_rater 36_600 ac cr914 ec12 fairwind/;

my $ok=exists $good{$testval} ? 1 : 0;
# or simply: my $ok=exists $good{$testval}

print 'Test result: ', $ok;


hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: text file to xml to database

2006-02-11 Thread John Doe
I BioKid am Samstag, 11. Februar 2006 20.39:
> Dear All,

Hi again

> We have a text based database, now we want to implement web services for
> the for people around the world for a programmatic access to our  server.

This is a quite general task. I think the people on this perl list would help 
for the perlish part(s) of the task, provided adequate infos.

> Our databse at the moment is not technically a database - 
> its only a server which retreive server 

Never heard about servers retrieving servers.

You expect people to take their time to provide help for you.
So *please* take a sufficient amount of time to at least reread what you 
wrote.

> and present it on browser according to query say id no like 6523  or name 
> like foo etc. 

This gives a hint that you reference the resources by id and/or name.
But it's still unclear how your current text data is organised.

Generally, perl is great in taking textual input and reorganise/modify it.

> First we want to transfer this data to xml 
> then we need to put it in a database,

Why XML? Just as an intermediate format, or do you intend to use it also, 
besides the data hold in the database? Or do you want to store xml in the 
database?

> Regarding XML - i dont have much idea
> -  we are planning for a PGSQL db 

[snip]

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: text file to xml to database

2006-02-11 Thread John Doe
I BioKid am Samstag, 11. Februar 2006 17.47:
> hi all,

Hi

There are reasons why you didn't get answers you like.

> I need technical advice from all perlbuddies,

There are quite a lot of perlbuddies...

> I have 2 text files and I want to convert it to XML and then to a
> database. It will be really helpfull, if you could give me a proper
> technical descritption to do it using PERL.like which module should i use,
> how to parse my text file to xml and how to store xml in PG /MySQL db

I think anybody who tries to answer needs as a prerequisite a 
*proper problem description* (e.g. what text structure; what xml structure; 
why via xml; what db layout; intended usage...)
from you first, and prefers to see what you already tried and what went wrong.

See also:
search.cpan.org for perl modules
dev.mysql.com for a description of mySQL

hth,
joe

[snip]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: array iteration problem

2006-02-08 Thread John Doe
JupiterHost.Net am Mittwoch, 8. Februar 2006 15.51:
> > use strict; # forces declaring variables
> > use warnings;
>
> yep yep :)
>
> >>@cpv_codes=('a','a','a','a','b','b','b','c','c','d');
> >
> > my @letters=(qw{ a a a a b b b c c d });
>
> No neeed for the (), which also make sit easier to write and to look at :)

Nice, I never considered omitting the (), thanks :-)

[...]
> > $hash{$_}++ for @letters;
>
> Good point, better than the map{} I just sent
>
> > print map "$_\t$hash{$_}\n", sort keys %hash;
>
> Not sure why you're using map here?

because print is only called once and not for every iteration. 
Look at the following benchmark:

use strict;
use warnings;
use Benchmark;
my @words='word' x 10;
timethese(1000, {
  'for' => 'print $_ for @words;',
  'map' => 'print map {$_} @words;'
});


Benchmark: timing 1000 iterations of for, map...
   for: 14 wallclock secs ( 9.18 usr +  0.00 sys =  9.18 CPU) @ 
1089324.62/s (n=1000)
   map:  5 wallclock secs ( 3.55 usr +  0.02 sys =  3.57 CPU) @ 
2801120.45/s (n=1000)


> print "$_\t$hash{$_}\n" for sort keys %hash;
>
> Also since strict and warnings have been recommended I might also poitin
> outthat %hash is a *very* bad name for a hash, its very ambiguouse and
> hard to maintain, 

Why is %hash a very bad name? 
Is @array also a bad name?
And what's the relationship with using strict and/or warnings?

> The entire thing is clearly written as: 
[...]

greetings
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: array iteration problem

2006-02-08 Thread John Doe
Graeme McLaren am Mittwoch, 8. Februar 2006 14.53:
> Hi all, I have the following code:

Hi Graeme

> # code

use strict; # forces declaring variables
use warnings;

> @cpv_codes=('a','a','a','a','b','b','b','c','c','d');

my @letters=(qw{ a a a a b b b c c d });

# qw (quote words) makes it easier to write and to look at :-)

> my %hash;
> foreach (@letters) {
> $hash{$_}++;
> print "$_\t $hash{$_} \n";
> }
> 
>
> and it prints:
>
> a1
> a2
> a3
> a4
[...]
> d1

The reason for that is that you print $hash{$_} *while* building it. 
What you see is how many times the just found char (in $_) has been seen in 
the array from its beginning to the current position.

> What I really need is:
>
> a = 4
> b = 3
> c = 2
> d = 1

Apart from Jeff's solution, there is also a shorter way:

$hash{$_}++ for @letters;
print map "$_\t$hash{$_}\n", sort keys %hash;

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: how to get filehandle-lock effective accross multi-process

2006-02-07 Thread John Doe
Jeff Pang am Dienstag, 7. Februar 2006 10.47:
> hello,lists,
Hello Jeff
> I open a file and obtained a filehandle.then I fork a child and access this
> file in child (via the duplicate filehandle from parent).If both parent and
> child are writting to the file at the same time,the things should become
> terrible.So I should use the 'flock' call to lock the filehandle.But I find
> just in the same process,the flock is effective.In other words,when I flock
> the filehandle in child,the effect of 'flock' mean nothing to parent,and
> parent can still write to the file. the test code is shown as below:
>
> use strict;
> use warnings;
[...]
>
> when this code run,both parent and child can write to the same file,and
> maybe at the same time.
>
> How can I resolve this problem?thanks.

Seems that the flock is implemented as *advisory* lock as stated in
perldoc -f flock
.

The solution lies in the appropriate usage of flock, that means to use locking 
for every access (try) to the resource. Since both accesses are within your 
code, you have 100% control about that :-)

hth,
jo

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Fwd: Re: dbm again

2006-02-06 Thread John Doe

> >>>Anders Stegmann 02/06/06 1:02 pm >>>
>
> Thaks for replying!
>
> The hash has only one key, so it sould be okay.
> I get the output:
>
> Can't use string (ARRAY(0x648290)) as an ARRAY ref while strict refs in
> use at testhash6.pl line 8.
>
> When I run the script.
>
> It seems like I am somehow dealing with a reference to an array!? Or
> what?


Hi Anders

It's not easy to find a line 8 with a try to derefence an array in your 
script :-)

Yes, the error tells you that something that has been an arrayref once is used 
as a string and tried to be derefenced.

You use an arrayref (on the right side) in the line

>$hash{$key1} = [$en, $to, $tre];

You can have a look at this data structure (and any other you like) with 
Data::Dumper, by putting code like below into your script:

use Data::Dumper;
warn Dumper \%hash;

The error occurs because of your line

>print $dbm_hash{$key}[2];

It seems that nested structures are not supported in the *dbm implementation, 
since at the beginning of your code it's possible to

print $hash{$key1}[2];

resulting in 'nul'.

I did not go further into the docs, and won't, and have never used dbmopen. 

It's deprecated. I think as a beginner you should not use deprecated things. 
Please read

perldoc -f dbmopen

and follow the advice there :-)

hth, joe



[top post history:]
> >>>John Doe <[EMAIL PROTECTED]> 02/06/06 12:55 pm >>>
>
> Anders Stegmann am Montag, 6. Februar 2006 12.30:
> >Hi!
>
> Hi Anders
>
> >Can anyone tell me why this script doesn't work?
> >
> >
> >use strict;
> >use warnings;
> >
> >my %hash = ();
> >
> >my $key1 = 'nul';
> >my $en = 'en';
> >my $to = 'to';
> >my $tre = 'tre';
> >
> >
> >$hash{$key1} = [$en, $to, $tre];
> >
> >dbmopen(my %dbm_result_hash, 'hash_database', 0666) or die cannot save
> >database_name to dbm\n;
>
> No quotes around the string after die. This is a syntax error.
>
> >%dbm_result_hash = %hash;
> >
> >dbmclose(%dbm_result_hash);
> >
> >dbmopen(my %dbm_hash, 'hash_database', 0666);
> >
> >my ($key) = keys %dbm_hash;
>
> Not shure if this is intended. $key contains the first key of the list
> of
> keys from %dbm_hash, which itself has not a specific order.
>
> >print $dbm_hash{$key}[2],\n;
> >
> >dbmclose(%dbm_hash);
> >
> >exit;
>
> No need for an exit at the end of a script.
>
> btw, from
>
> perldoc -f dbmopen:
>
> dbmopen HASH,DBNAME,MASK
>   [This function has been largely superseded by the tie
> function.]
>
>
> hth,
> joe
>
> --
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
> <http://learn.perl.org/> <http://learn.perl.org/first-response>

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




Re: dbm again

2006-02-06 Thread John Doe
Anders Stegmann am Montag, 6. Februar 2006 12.30:
> Hi!

Hi Anders

> Can anyone tell me why this script doesn't work?
>
>
> use strict;
> use warnings;
>
> my %hash = ();
>
> my $key1 = 'nul';
> my $en = 'en';
> my $to = 'to';
> my $tre = 'tre';
>
>
> $hash{$key1} = [$en, $to, $tre];
>
> dbmopen(my %dbm_result_hash, 'hash_database', 0666) or die cannot save
> database_name to dbm\n;

No quotes around the string after die. This is a syntax error.

> %dbm_result_hash = %hash;
>
> dbmclose(%dbm_result_hash);
>
> dbmopen(my %dbm_hash, 'hash_database', 0666);
>
> my ($key) = keys %dbm_hash;

Not shure if this is intended. $key contains the first key of the list of  
keys from %dbm_hash, which itself has not a specific order.

> print $dbm_hash{$key}[2],\n;
>
> dbmclose(%dbm_hash);
>
> exit;

No need for an exit at the end of a script.

btw, from 

perldoc -f dbmopen:

dbmopen HASH,DBNAME,MASK
   [This function has been largely superseded by the "tie" 
function.]


hth, 
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Duplicates elements in an array

2006-02-06 Thread John Doe
anand kumar am Montag, 6. Februar 2006 08.34:
> Hi all
>
>  I have an array with hundreads of elements in it. Can anyone
> suggest the easiest way to keep only the duplicate elements in the array.

Hi Anand

Depends a bit if you want to keep all duplicates of a duplicate element or 
just one of it. Your question is not clear in this respect.

An easy way would be to consult the perlfaq:

perldoc -q 'duplicate'


hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: On Focus

2006-02-06 Thread John Doe
>   On 2/5/06, Ron Smith wrote:
> > Hi all,
> >
> > I've been looking for this all over, but can't seem to find a link. Is
> > there a Perl or PerlScript equivalent to the JavaScript or vbscript
> > on-focus function? If there is, could someone please, point me in the
> > right direction.
> >
>
> Omega -1911 <[EMAIL PROTECTED]> wrote:
> Can you tell us what exactly it is that you are trying to do?
>
> Ron Smith am Montag, 6. Februar 2006 01.35:
> Yes, I'm trying to have the "blinking cursor" start in a specific text
> field, on a web page, when the page loads in the browser.

Hi Ron

There is no such thing as a perl equivalent for the javascript onfocus 
attribute.

Javascript handlers are interpreted by the javascript engine of a browser, 
based on the definition of this attribute and its associated javascript 
handler code, both defined in the (x)html code.

Perl on the other side is a script language that can be interpreted by the 
server (via cgi, modperl etc.) to produce html page source code - but can not 
be given to the browser to be interpreted by it.

What you want probably is something that produces the onfocus attribute on the 
server side, along with producing the html code.

There are lots of modules on search.cpan.org that help to produce html source 
and even javascript code. 

Check out the CGI module, 
http://search.cpan.org/~lds/CGI.pm-3.15/CGI.pm,
and search for the word javascript.

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Saving Content of HTTP::Response Directly To Disk

2006-02-04 Thread John Doe
Stephen Le am Sonntag, 5. Februar 2006 04.09:
> I'm writing a download manager in Perl and using the LWP library of
> Perl modules.
>
> Is there any way I can save the contents of a HTTP::Response object
> directly to disk? I don't want particularly large requests to be
> cached into memory.

Storable (fast) or Data::Dumper (readable) could be useful to store and 
recreate HTTP::Response objects.
Or, at a higher level, Cache::FileCache (which can store without expiring)

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: How to compare hashes to find matching keys with conflicting values.

2006-02-03 Thread John Doe
Angus am Freitag, 3. Februar 2006 10.13:
> Joe,
>
> Thank you for taking the time to explain this bit of code.  I have spent
> some time trying to understand the ternary operator (?:) this evening and I
> think it is making more sense.  In the past I have seen this operator and
> moved on in favor of using if/then/else statements but I can see how in
> this example it is much simpler to evaluate the EXPR with a ternary than to
> use code blocks.  I can now see mostly how this expression works in your
> example.  I see that the first expression says $actual{$_} equal
> $register{$_} if this is true then $_ equals the hostname. 

gotcha :-)


> But, if this 
> statement is false then I see that we dereference the $_ values in both
> Arrays.

Not quite shure what you mean here

> When I do run this code though it seems to print out the memory address for
> the hostname reference which I think means it is not being dereferenced
> correctly but I don't see how it differs form the else part of the print
> statement
>
> ARRAY(0x816e00c) differs:actual 164.72.119.175 <-> register 164.72.119.179
> ARRAY(0x816e03c) differs:actual 164.72.123.43 <-> register 164.72.21.43
> host3 is ok
> ARRAY(0x819bed4) differs:actual 164.72.98.89 <-> register 164.72.8.89
> host5 is ok

Hm, indeed (now after testing) - it is my fault, but it motivated you to go 
into the details :-)

I posted a correction to my first version, and I did not consider all side 
effects of the faulty first version.
Further, my code misses an information: The host name in the case the two IPs 
differ.

I'll post below the code in the first version (with the mentioned missing 
info), it's runnable now :-)

Then, some snippets for a modification follows to get the host name in the 
result also in the case of differing IPs.

=== BEGIN first version ===
#!/usr/bin/perl

use strict;
use warnings;

my %actual = (
"host1" => "164.72.119.175",
"host2" => "164.72.123.43",
"host3" => "164.72.45.98",
);

my %register = (
"host1" => "164.72.119.179",
"host2" => "164.72.21.43",
"host3" => "164.72.45.98",
);

my @res = map {
   ( $actual{$_} eq $register{$_} )
   ? $_
   : [ $actual{$_}, $register{$_} ] ### (A) ###
} sort keys %register;

foreach my $e (@res) {
  if (!ref($e)) {
print "$e is ok\n";
  }
  else {
# corrected the following print, since host name is not in @res in 
# this case ### (B) ###
print "Differing IPs (host info missing): ",
   "actual @{[$e->[0]]} <-> register @{[$e->[1]]}\n";
  }
}
=== END first version ===

Ok, now to get the host name into the result, there are several possibilities.
The easiest way is to modify the (A) and (B) lines above like:

: [ $_, $actual{$_}, $register{$_} ] # host name, IP 1, IP 2

print "host @{[$e->[0]]} differs: ",
"actual @{[$e->[1]]} <-> register @{[$e->[2]]}\n";
# note that the indexes have changed.


> I still have some ways to go with really understanding this but I am
> closer.

Yes, I can see that! Good luck!

> P.s. Your English is probably better than mine; I wouldn't know it wasn't
> your first language if you didn't mention it.

Thanks :-)
(learning english is the main reason for me to be on the list)

joe

[whole history snipped away]

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Closing and Re-Opening the Same File Problem

2006-02-02 Thread John Doe
[EMAIL PROTECTED] am Donnerstag, 2. Februar 2006 19.35:
> Here's my problem:
>
> I am writing a program that opens one file  (pricedata.csv)  as input, does
> some processing, and opens a new file  (PriceDataRfrmtd1.txt)  for ouput.
> Subsequently I close both files.  So far so good. Now, within the same
> program, I attempt to re-open the previous  output (i.e.
> PriceDataRfrmtd1.txt) as input and perform some processing and I  begin to
> run into some problems. More specifically, here's a segment of my  code:

This shouldn't be any problem. I guess the problem lies in your code.
Please provide the relevant code; the one below contains no opening/closing of 
files, and...


>
>
> while() {
>
>   $TheRec = $_;
> chomp($TheRec);
>
>   @Row =  split(/\s+/, $TheRec);
>
>   print "[EMAIL PROTECTED] = @Row\n";
>
>   $Date = $Row[0];
> $AdjOpen = $Row[2];
> $AdjClose =  $Row[4];
>
>
> print "\n\$Date = $Date\n";
> print "\n\$AdjOpen =  $AdjOpen\n";
> print "\n\$AdjClose =  $AdjClose\n";
>
> exit;

...exits the program after having read the first line of .


> } # End of while()

[snipped description of first array element conaining whole line]


hth
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: How to compare hashes to find matching keys with conflicting values.

2006-02-02 Thread John Doe
Angus am Donnerstag, 2. Februar 2006 10.14:
> John,

Hello Angus

> Well that works perfect now my issue is to understand what you have
> provided for me.  I see that we are creating an array called res however I
> am not sure what map is doing.  I did read the perldoc info on map but I am
> still confused on how it is being used here.  I see from the perldoc that I
> could use it like this
>
> %register = map {$register($) => $_ @array;
> print "@array\n";

No, this is syntactically incorrect and wouldn't do anything useful.

> This would I think create an array based on the values contained in the
> register hash.  

No; in an assignement

  = 

the left part is made from the expression on the right.

> But, I would have now way to link them back to the keys
> from register as now they would be numerically ordered in the array instead
> of being linked to the hostname key.
>
> So I am looking at your example:
> %actual = map ($actual{$_} eq $register{$_})

This is not my example... and syntactically incorrect.

> This I think says each key eq to the other key value.  

The part within the braces does a comparison between $actual{$_} and 
$register{$_}. Result is true or false.


> Next you use a ? mark which I understand means that the previous 
> values are optional, 

No, its part of the ternary ?: operator (see perldoc perlop).

my $var = $x ? $y : $z

is the same as

my $var;
if ($x) {
  $var=$y;
}
else {
$var=$z;
}

> which  
> in this case if the are not equal are they then not included in the $_
> variable.  But if they are eq then they are included in the $_ value which
> means they are placed back into the hashes?  After this the register hash
> is sorted but I don't understand why.

It's because of the sort (see perldoc -f sort) in the expression. The keys of 
%keys are sorted with it before it goes through the "map pipe".

> The next code block iterates through the res array and unless it finds a
> reference?  I did a perldoc on ref and see that it returns a non-empty
> string if EXPR is a reference.  So now I think we created an array of
> hashes with the @res and map combo, is that correct?

Ok, let's analyse in detail:

[...]
> my %actual = (
> "host1" => "164.72.119.175",
> "host2" => "164.72.123.43",
> "host3" => "164.72.45.98",
> );
>
> my %register = (
> "host1" => "164.72.119.179",
> "host2" => "164.72.21.43",
> "host3" => "164.72.45.98",
> );
[citation removed, reformatted:]

my @res = map {
   ( $actual{$_} eq $register{$_} )
   ? $_
   : [ $actual{$_}, $register{$_} ]
} sort keys %register;

The whole expression is to read from bottom to top; %register is the start; it 
is handled in 3 ways each after the other, resulting in @res.

1st, the keys are taken (keys %register).
2nd, the keys are sorted (sort)
3rd, map creates a new structure.

You could image some sort of "pipe" with stations:
entity:@res <- do:map <- do:sort <- do:keys <- entity:%register

Note that @res does nowhere occur on the right side: It's the result; nothing 
is inside it before the expression on the right side of the '=' is evaluated.


Now to the map part: ... <-- map {  } <-- ... : 
It takes something at the right, mangles it, and puts it out on the left.
(Note the {}-braces are part of the map; it's one of it's two syntax).

Within map{}, $_ contains the sorted keys of %register; one by one is mangeld 
by map{}. $_ is a scalar, fed to map on the right, and map returns a scalar 
on the left.

The scalar is either the key ( $_ ) or an arrayref [ ... ], depending of the 
result of the comparison, taken from after ? or after : .

What the map does here (for every $_ separate) in words:
"Compare the value from %actual keyed by $_ with the value from %register 
keyed by $_. If they are equal (means: if the IPs are equal), return the key 
(means: hostname); otherwise, return the two different values (means: the two 
different IPs) within an arrayref."


I hope this helps and my english was not too confusing.

Just play around with map to get the feeling. I remember that it is not easy 
to understand at the beginning, but if you get the idea, you won't miss it, 
because it allows to do complex actions in a very short way.

joe



[nothing new below]
> foreach my $e(@res) {
> unless(ref($e)) {
> print "$e is ok\n";
> }
> else {
> print "$e differs:actual @{[$e->[0]]} <-> register @{[$e->[1]]}\n";
> }
> }
>
>
> -Original Message-
> From: John Doe [mailto:[EMAIL PROTECTED]
> Sent: Wednesday, February 01, 2006 2:45 AM
> To: beginners@perl.org
> Subject: Re: How 

Re: Escaping large chunk of text for insertion into mysql

2006-02-01 Thread John Doe
Kevin Old am Mittwoch, 1. Februar 2006 13.44:
> Hello everyone,
>
> I have a large chunk of data that I need to insert into a text or blob
> field in mysql.  I've tried all the usually escaping it, but nothing
> seems to work.  I'm even using dbh->quote as I thought it might help.
>
> Here's my code:
>
> my $sth = $dbh->prepare("insert into nascar_media values(
> personal_characteristics ) (?)");
> $sth->execute( $dbh->quote($vals[13]) );
>
> Not that it really helps, here's the DBD::mysql error returned:
>
> DBD::mysql::st execute failed: You have an error in your SQL syntax;
> check the manual that corresponds to your MySQL server version for the
> right syntax to use near '('\'Married: Arlene. Children: Amy
> (10/14/72), Twins Rachel and Heather (10/31/7' at line 1 at ./nm4.pl
> line 181.

The first single quote in the error msg is from the msg itself. The error 
occurs at the '('. So, your mysql syntax is wrong, independently from the 
inserted value. Just thest the statement at the mysal cmdline.

Then, when using placeholders, quote() is not necessary; it's done 
automagically.

I did not test it, but try the following (also note the missing field name 
'personal_characteristics') - it is assumed that the table only consists of 
one field.

$dbh->prepare( 'insert into nascar_media values (?)' );
$sth->execute( $vals[13] );

Check 
man DBI
http://dev.mysql.com/

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: How to compare hashes to find matching keys with conflicting values.

2006-02-01 Thread John Doe
Sorry for another mail, but there are too many typos:

> Also untested:
>
> # If no conflict, value is hostname.
> # If conflict, value is arrayref with the two different IPs
> #
> my @res = map {
>   ($actual{$_} eq $register{$_})
>   ? $_
>   : [$actual{$_}, $register{$_}]
>
> } sort keys %register;
>
> foreach my $e (@res) {
>   if (ref($e)) {

This should read
   unless (ref($e)) {

> print "$e is ok\n";
>   }
>   else {
> print "$e differs: actual @{[$e->[0]]} <-> register @{[$e->[1]]}\n";
>   }
> }
>
> I think this should give you an idea.
> To look op any perl funktion, type:

up, function

>
> perldoc -f FUNCTIONNAME
>
> The man page for operaters:

operators

Nice day to all :-)

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: How to compare hashes to find matching keys with conflicting values.

2006-02-01 Thread John Doe
Angus am Mittwoch, 1. Februar 2006 10.04:
> Hello,
>
>
>
> I am trying to write a little script that will compare two hashes with the
> same keys but conflicting values.  I have found some great examples of how
> to compare hashes and locate common keys or missing keys (in the cookbook).
> I have also found a great example of how to locate duplicate keys in two
> hashes (also in the cookbook) but nothing that helps with this question in
> particular.  The following example is based on a pair of hashes using
> hostname and ip address information.

The following script never compiled due to syntax errors...
(Push, My, etc.)

> #!/usr/bin/perl
>
> use strict;
>
> use warnings;
>
>
>
> # This hash represents the actual data, in other words what the machines
> have acquired for an ip address.
>
> my %actual = (
>
> "host1" => "192.168.119.175",
>
> "host2" => "192.168.123.43",
>
> "host3" => "192.168.45.98",
>
> "host4" => "192.168.98.89",
>
> "host5" => "192.168.67.123",
>
> );
>
>
>
> # This hash represents the preferred information, or what I would like to
> assign to my hosts.
>
> my %register = (
>
> "host1" => "192.168.119.179",
>
> "host2" => "192.168.21.43",
>
> "host3" => "192.168.45.98",
>
> "host4" => "192.168.8.89",
>
> "host5" => "192.168.67.123",
>
> );
>
>
>
> My @common = ();  # it seems with this I at least have an array that now
> maintains a list of host names that definitely exist in both hashes
>
> Foreach my $host (keys %actual) {
>
> Push (@common, $host) if exists $register{$host);
>
> }

@common will contain all host names, since %actual and %register have the same 
keys.

> # I also sort of wondered if I could use the values function to compare the
> hashes but this just resulted in an array with every element in it.
>
> My @not_common = ();
>
> Foreach my $host (values %actual) {
>
> Push(@not_common, $host) unless $register{$host} == $host; }
>
> Print "@not_common\n";
>
> # but as I am sure you can imagine this doesn't work so well..

use eq instead of == to compare non numeric values.

> # at this point I think I should use references to insert the host name and
> compare the hosts but I am not sure how I would do this.
>
> # so what I thought might also work is simply comparing the two hashes like
> this
>
> My @match = ();
>
> If ($actual{$host1} == $register{$host1}) {
>
> Print "They match!\n";}
>
> Else {
>
> Print "no match. \n";}

$host1 not defined and wrong comparison operator.

> # The print statements are just tests, if it had worked I thought I could
> open a filehandle to a flat file and write out the match and conflicts.
>
>
>
> So, hopefully that is enough to explain what I am trying to do in spite of
> my feeble attempts to solve the question.
>
>
>
> Thanks in advance to anyone willing to point out the err my ways,

Also untested:

# If no conflict, value is hostname.
# If conflict, value is arrayref with the two different IPs
#
my @res = map { 
  ($actual{$_} eq $register{$_})
  ? $_
  : [$actual{$_}, $register{$_}]
} sort keys %register;

foreach my $e (@res) {
  if (ref($e)) {
print "$e is ok\n";
  }
  else {
print "$e differs: actual @{[$e->[0]]} <-> register @{[$e->[1]]}\n";
  }
}

I think this should give you an idea.
To look op any perl funktion, type:

perldoc -f FUNCTIONNAME

The man page for operaters:

perldoc perlop

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Hash problem

2006-01-30 Thread John Doe
Andrej Kastrin am Montag, 30. Januar 2006 16.50:
> John Doe wrote:
> >Andrej Kastrin am Montag, 30. Januar 2006 10.14:
> >>Dear all,
> >>
> >>I have bar separated file:
> >>name1|345
> >>name2|201
> >>...
> >>
> >>I store it into a hash;
> >>while () {
> >>   chomp;
> >>   ($name,$score) = split (/\|/,$_);
> >>   $hash{$name} = $score;
> >>}
> >
> >Let's assume the resulting hash is %scores.
> >
> >>Then I have second file:
> >>ID - 001
> >>NA - name1
> >>NA - name2
> >>
> >>ID - 002
> >>NA - name2
> >>NA - name4
> >>...
> >>
> >>I match all ID's and NA's:
> >>
> >>while () {
> >>   chomp;
> >>   if (/^ID/ {
> >>   $ID = substr($_,5);
> >>   }
> >>elseif (/^NA/) {
> >>$NA = substr($_,5)
> >>}
> >>
> >>Now I have to do somethig like;
> >>001 | 345+201
> >>So, I want to read ID and NA fields from second file and then with each
> >>ID print the sum of scores from first file.
> >>Any suggestion. Which structure should I use to do that. Thank's in
> >>advance.
> >
> >Now you could parse FILE_B and use another twodimensional hash to
> > accumulate the scores by ID for each name. The loop could look like
> > (untested):
> >
> >my %sums;
> >my $id;
> >while () {
> >   chomp;
> >   next if (($id)=$_=~/^ID - (\d+)/);
> >   next unless my ($na)=$_=~/^ID - (\w+)/;
> >   $sums{$id}->{$na}+=$scores{$na};
> >}
> >
> >foreach my $id (sort keys %sums) {
> >   print "ID $id\n";
> >   foreach my $name (sort keys %{$sums{$id}}) {
> >  print "name: $name - scores: ",
> > $sums{$id}->{$name}, "\n";
> >   }
> >}
> >
> >(All handling of possible errors is missing here)
> >
> >
> >hth,
> >joe
>
> I'm totally confused now and I have no more ideas... Thank's for your
> reply Joe, but I didn't manage. Here is the more real example:

My answer above is obviously not appropriate to the following quite different 
example...

[1]
> First file: (I modify it)
> 270|Germany|Hospitals|Poland
> 272|Germany|History
> 273|Physiology|Poland|Portraits

Quite different from:

   name1|345

[2]
> Second file:
> Germany|100
> History|200
> Hospitals|50
> Poland|50
> Physiology|10
> Portrait|10
(I assume you mean 'portraits' here)

Quite different from:

   ID - 001
   NA - name1
   NA - name2

   ID - 002

[3]
> Output file:
> 270|100|50|50|200 #270 is the key in table 1; 
>  100, 50, 50 are values for 
>   nouns from second file, 200 is the sum of them
> 272|100|200|300
> 273|10|50|10|70

Ok, you want [3] from [1] and [2]?
If yes, here is the script, I tested it, and it produces the output you like:

#!/usr/bin/perl

use strict;
use warnings;

# Make a lookup hash of file 2.
# haskeys are keys, hashvalues names of the file.
# It is assumed that a name only occurs once in the file.
#
my %lookup;
open (my $fh2, '<', 'file2') or die;
while (<$fh2>) {
  chomp;
  my ($name, $score)=split /\|/;
  $lookup{$name}=$score;
}
close $fh2 or die;


# Now in every line of file1 all names are replaced
# by their score (?) value found in the lookup hash
# and a sum is added at the end. The line is
# directly printed out.
#
open (my $fh1, '<', 'file1') or die;
open (my $fh3, '>', 'file3') or die;
while (<$fh1>) {
  chomp;
  my ($num, @entries)=split /\|/;

  # replace names by scores. If no score found,
  # take score=0
  #
  @entries=map {$lookup{$_}||0} @entries;

  my $sum=0;
  $sum+=$_ for @entries;

  print $fh3 join '|', $num, @entries, $sum;
  print $fh3 "\n";
}
close $fh1 or die;
close $fh3 or die;




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




Re: Hash problem

2006-01-30 Thread John Doe
Andrej Kastrin am Montag, 30. Januar 2006 10.14:
> Dear all,
>
> I have bar separated file:
> name1|345
> name2|201
> ...
>
> I store it into a hash;
> while () {
>chomp;
>($name,$score) = split (/\|/,$_);
>$hash{$name} = $score;
> }

Let's assume the resulting hash is %scores.

> Then I have second file:
> ID - 001
> NA - name1
> NA - name2
>
> ID - 002
> NA - name2
> NA - name4
> ...
>
> I match all ID's and NA's:
>
> while () {
>chomp;
>if (/^ID/ {
>$ID = substr($_,5);
>}
> elseif (/^NA/) {
> $NA = substr($_,5)
> }


> Now I have to do somethig like;
> 001 | 345+201
> So, I want to read ID and NA fields from second file and then with each
> ID print the sum of scores from first file.
> Any suggestion. Which structure should I use to do that. Thank's in
> advance.

Now you could parse FILE_B and use another twodimensional hash to accumulate 
the scores by ID for each name. The loop could look like (untested):

my %sums;
my $id;
while () {
   chomp;
   next if (($id)=$_=~/^ID - (\d+)/);
   next unless my ($na)=$_=~/^ID - (\w+)/;
   $sums{$id}->{$na}+=$scores{$na};
}

foreach my $id (sort keys %sums) {
   print "ID $id\n";
   foreach my $name (sort keys %{$sums{$id}}) {
  print "name: $name - scores: ", 
 $sums{$id}->{$name}, "\n";
   }
}

(All handling of possible errors is missing here)


hth,
joe


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Simple RegEx expresion

2006-01-25 Thread John Doe
George Homorozeanu am Mittwoch, 25. Januar 2006 16.12:
> I need it with RegEx, that's my problem.
>
> Thanks,
>
> George.
>
> "Xavier Noria" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
> news:[EMAIL PROTECTED]
>
> > On Jan 25, 2006, at 12:23, George Homorozeanu wrote:
> >> I am very new in RegEx and I want to be able to write an expresion  that
> >> does
> >> the following:
> >>
> >> Return all the characters from a string starting from the 5-th
> >> character.
> >
> > You want to do it with a regexp for some particular reason? That's  the
> > job of substr().

Could you have a look at the following man page (type it at the cmdline):

perldoc perlretut

This is a (short) tutorial about regexes. Although this list is for beginners, 
I personally feel that it is advisable to have a minimal understanding about 
the code one writes - and your regex question is *very* basic and described 
in the man pages.

You say that you want to be *able* to *write* this expression, so I don't 
think my post is impolite.

If, after reading the manual and having *tried* to write the regex, you still 
need help, post again.

(The full regex details you can find with
perldoc perlre)

hth, joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Quick regex question

2006-01-24 Thread John Doe
Chris am Dienstag, 24. Januar 2006 22.35:
> Hi list,
>
> I am not sure if there is a proper name for this but was having some
> difficulty searching for it.
>
> Basically I have data in a file that is between two different
> characters, for example:
>
> # data data
> data
> data data data *
> # more dataaa
> mor *
>
> Basically I want to slurp that file in, then search for # and extract
> all the data up to the * and print it, new line, next set of data.

I assume you mean that the whitespace after '#' and before '*' is not part of 
the data (else, remove the \s* in the regex below).

The following just one (of the shorter) way to do it; read the expression 
beginning with 'print' bottom-up:

==
#!/usr/bin/perl

use strict;
use warnings;

local $/;
my $content=;
print join "\n",
   map { do {$_=~s/\n/ /gs; $_} }
   $content=~/#\s*(.*?)\s*\*/gs;

__DATA__
# data data
data
data data data *
# more dataaa
mor *
==

see

perldoc -f map
perldoc -f do
perldoc perlre

and for opening/closing an external file:
perldoc -f open
perldoc -f close

hth, joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Array problem

2006-01-22 Thread John Doe
Andrej Kastrin am Montag, 23. Januar 2006 07.55:
> I wrote simple script, which have to concatenate multiple lines into
> array and then print each element of tihis array:
>
> I don't know where is the problem, Please, help!

The basic problem is that you try to print the result within the (while) loop 
that is building the result array. What your script does:

It shows the content of the array after every step of building it.

Besides that, there are other improvements - see inline:

# Alway start with:

use strict; # forces to declare variables
use warnings; # helpful for finding (potential) errors

> open INPUT,"<$ARGV[0]";

# missing error checking:
open (INPUT, '<', $ARGV[0]) or die "Can't open file: $!";

my @array;

> while ($line=){

while (my $line=){

> push (@array,$line);

> foreach $i(@array){
foreach my $i(@array){
> print $i;
>}

The above foreach loop should be outside of the while loop.

When you have to declare the variables (because of 'use strict'), you have to 
think about the scope of it (@array in this case). @array is defined in the 
same scope as the array building while loop. After the while, it is built, 
and you can use it. Basically, you have the following work:

- declare array
- fill array
- use array

> }
>
> Input is e.g.
> line 1
> line 2


hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: File Parsing

2006-01-22 Thread John Doe
William Black am Sonntag, 22. Januar 2006 15.33:
> Hello,
>
> I'm reading from a file.  I'm trying to read in five lines at a time where
> each line has a newline and then process the lines into separare variables.
> For example,
>
> Input File
> -
> Stevens,
> Craig A Triangle Family Care PA
> 106-A Ridgeview Dr
> Cary, NC
> View Profile & Phone | Appointment Services 0.4
> Once the lines are read in, I want to store 'Stevens' into a Lname
> variable, 'Graig' in a Fname variable, 'A Triangle Family Care PA' into
> BusName variable, '106-A Ridgeview Dr' into a Address variable, 'Cary' into
> a City variable, and 'NC' into a state variable.  Could someone point me in
> the right direction?

A great part of the direction is the answer by Shawn to your previous answer, 
where you intended to read 4 lines at a time instead of 5.

In Shawn's answer are the two lines:

   # process @lines
   print Dumper [EMAIL PROTECTED];

The first tells you where to process the accumulated lines,
the second shows you the structure of @lines.

Now you want parts of the lines assigned to some variables.
For that, please read about the possibilities to get substrings from a 
string:

perldoc -f split
or, for more complicated cases:
perldoc perlre 
and the other manuals mentioned therein at the bottom.

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: problems with subroutine prototype checking

2006-01-20 Thread John Doe
Hello Gavin

Gavin Bowlby am Freitag, 20. Januar 2006 01.43:
[...]
> I probably wasn't clear in my original posting, the problem I'm having
> is that the code sample I gave *does* compile successfully, 

I don't think so, because you try to use packages that are not declared.

> without 
> errors. I don't need to export anything to get it to compile
> successfully.
>
> I want it to *fail* compilation with an error callout about a parameter
> count mismatch.
[...]

Your code in the first post misses a lot of things, for example the package 
declarations, 'use strict', 'use warnings', the usage of the Exporter module 
(or calling the sub qualified with the package name) as Jimmy said.

This makes it difficult to help you.

Please post the actual test code you tried (trimmed to the relevant parts).

greetings joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Using XML::Simple [SORRY - correction]

2006-01-19 Thread John Doe
John Doe am Donnerstag, 19. Januar 2006 12.43:

> $VAR1->{LayerList}->{LayerDetails}=
>[ map {%$_} @{$VAR1->{LayerList}->{LayerDetails}} ];

This should be:

$VAR1->{LayerList}->{LayerDetails}=
  [ map {values %$_} @{$VAR1->{LayerList}->{LayerDetails}} ];

(The 'values' omits the repeated 'Name' in the result)

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




Re: Using XML::Simple

2006-01-19 Thread John Doe
Bjorn Van Blanckenberg am Donnerstag, 19. Januar 2006 09.33:
> I have some elements in my xml that are empty but have attributes.
> I would like that I can group the element in function of Attribute Name.
>
> Status="Available">
>  
>
>
>
>  
>
>
> I read in I get
>
> $VAR1 = {
>'ID' => 'r060116_103344354_26',
>'Status' => 'Available',
>'LayerList' => {
> 'LayerDetails' => [
> {
>   'Name' => 'nl-BE'
> },
> {
>   'Name' => 'fr-BE'
> },
> {
>   'Name' => 'nl-NL'
> }
>   ]
>   },
>'Class' => 'Parameter'
>  };
>
>
> I would like it when the xml is readed in to became
>
> {
>   'ID' => 'r060116_103344354_26',
>  'Status' => 'Available',
>   'LayerList' => {
> 'LayerDetails' => [ 'nl-BE', 'fr-BE', 'nl-
> NL' ]
>   },
>   'Class' => 'Parameter'
> }
>   }
>
> I've tried to use
> # KeyAttr => [ list ]
> # KeyAttr => { list }
> # GroupTags => { grouping tag => grouped tag }
>
> even an combination of KeyAttri and GroupTags but don't get the
> desired output

Just in case it's not possible with XML::Simple, you could use a workaround on 
the result data structure by transforming it with:

$VAR1->{LayerList}->{LayerDetails}=
   [ map {%$_} @{$VAR1->{LayerList}->{LayerDetails}} ];

hth, joe


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Transform column into row

2006-01-19 Thread John Doe
Dr.Ruud am Donnerstag, 19. Januar 2006 00.49:
> John Doe schreef:
> > In constrast to the other presented solutions using a a hash slurping
> > all data from the intput file, the advantage of my solution is that
> > it is *capable to handle 300GB input files* even with 128MB RAM.
>
> Also in contrast is that your solution assumes sorted input, which
> wasn't anounced.

But it was present in the sample data. If it wasn't, I would have suggested a 
preliminary non-inmemory sort technique.

> The hash isn't slurping all data: only the unique values of the first
> column are stored.

I should have said "the hash and its contained arrayrefs", sorry for that and 
my bad english in general.


greets joe

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




Re: Transform column into row

2006-01-18 Thread John Doe
Andrej Kastrin am Mittwoch, 18. Januar 2006 10.49:
> Dear Perl users,
>
> what's the best way to  transform column table in row format. I know how
> to split each line according to delimiter and than put it separately
> into array, but I have more complicated problem (with multiple equal
> records in the first column)
>
> id001  text1
> id001  text2
> id001  text3
> id002  text23
> id002  text555
> id003  text666
>
> and want something like:
>
> id001 text1 text2 text3
> id002 text23 text 555
> id003 text666

Ok, in addition to my apologies, I present here the script I described in my 
last post.

In constrast to the other presented solutions using a a hash slurping all data 
from the intput file, the advantage of my solution is that it is 
*capable to handle 300GB input files* even with 128MB RAM. 


===
#!/usr/bin/perl

use strict;
use warnings;

# open input file here if source is not 

open (my $outf, '>', './andrey_kastrin.out.txt')
  or die "Can't open file: $!";

my $old_name='';
while () {
  chomp;
  my ($name, $value)=$_=~/^([\w]+)\s+(.*)$/;
  if ($old_name ne $name) {
print $outf "\n" if $old_name;
print $outf $_;
  }
  else {
print $outf ' ',$value;
  }
  $old_name=$name;
}
close $outf or die "Can't close file: $!";

# close input file here if source is not 


__DATA__
id001  text1
id001  text2
id001  text3
id002  text23
id002  text555
id003  text666
===


It outputs:

id001  text1 text2 text3
id002  text23 text555
id003  text666

I'm a nice guy, see?

joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Transform column into row (correction)

2006-01-18 Thread John Doe
John Doe am Mittwoch, 18. Januar 2006 15.30:
[...]
> Another way (I don's say a better :-) ) could be not using a data
> structure, but doing the transformation on the fly:
>
> - read a line of the input data
> - record the first or a new field name while scanning (id001 etc.)
> - if the field name is new / has changed, output it to a new file
> - if it is not new / has not changed, append the value(s)
> - repeat these steps

open input file and new output file

read a line of the input data and record the field name (id001 etc.)

if the field name is new / has changed, output a newline (exept for the first 
line), the field name and the value.
if it is not new / has not changed, output only the value.

read next line from input file and repeat procedure

close files

joe

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




Re: Transform column into row

2006-01-18 Thread John Doe
Paul Johnson am Mittwoch, 18. Januar 2006 13.53:
> On Wed, Jan 18, 2006 at 01:34:01PM +0100, John Doe wrote:
> > Andrej Kastrin am Mittwoch, 18. Januar 2006 10.49:
> > > Dear Perl users,
> > >
> > > what's the best way to  transform column table in row format. I know
> > > how to split each line according to delimiter and than put it
> > > separately into array, but I have more complicated problem (with
> > > multiple equal records in the first column)
> > >
> > > id001  text1
> > > id001  text2
> > > id001  text3
> > > id002  text23
> > > id002  text555
> > > id003  text666
> > >
> > > and want something like:
> > >
> > > id001 text1 text2 text3
> > > id002 text23 text 555
> > > id003 text666
> > >
> > > Thank's for any suggestions.
> >
> > My suggestion is that you show us what you tried so far, since this list
> > is not a script service.
>
> But he didn't ask for a script, he asked for suggestions on the best way
> to do something.

You are right. I apologize for that as well as for my tone. 
Partly it is due to my bad english, I miss the subtilities.

> [As a side note, and not directed specifically to John Doe, this list
> seems to be becoming a little less friendly to beginners than it used to
> be.  I think that is a shame.  

There are some people on the list, especially J.W. Krahn (and others), who are 
always very polite with any kind of questions :-)


[...]
> In most programming problems, I find that if you can design the correct
> data structures the code pretty much writes itself.  In this case, the
> correct data structure seems to be a hash of arrays.  See perldoc
> perldsc.  With this data structure, and the knowledge you already have,
> I would expect a solution to present itself.  If you still have
> problems, do as John Doe suggests, and come back to us with the code you
> have already tried.

Another way (I don's say a better :-) ) could be not using a data structure, 
but doing the transformation on the fly:

- read a line of the input data
- record the first or a new field name while scanning (id001 etc.)
- if the field name is new / has changed, output it to a new file
- if it is not new / has not changed, append the value(s)
- repeat these steps

joe

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




Re: Transform column into row

2006-01-18 Thread John Doe
Andrej Kastrin am Mittwoch, 18. Januar 2006 10.49:
> Dear Perl users,
>
> what's the best way to  transform column table in row format. I know how
> to split each line according to delimiter and than put it separately
> into array, but I have more complicated problem (with multiple equal
> records in the first column)
>
> id001  text1
> id001  text2
> id001  text3
> id002  text23
> id002  text555
> id003  text666
>
> and want something like:
>
> id001 text1 text2 text3
> id002 text23 text 555
> id003 text666
>
> Thank's for any suggestions.

My suggestion is that you show us what you tried so far, since this list is 
not a script service.

joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: interpolation

2006-01-16 Thread John Doe
Shawn Corey am Montag, 16. Januar 2006 16.55:
> 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";

As I understood "The Ghost", the starting point string already contains a 
literal '$variable': 'some perl $variable'.

I do not know the bigger picture of his problem, but I think an extensible way 
to replace a set of known names within a string by values would be (mirco 
templating system):

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

my %lookup=( 
   var=>'variable',
   other_var=>'another',
);

sub err {warn q(Unkown name '), shift, qq(' found\n)}

my $string='some $var $other_var $unknown';
$string=~s
   { \$([a-zA-Z_]+) }
   { exists $lookup{$1} ? $lookup{$1} : do {err($1), ''} }gxe;
print $string;
===

# prints: 
Unkown name 'unknown' found
some variable another

No interpolation involved, and the '$' sign preceding the names could be 
another one.

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




Re: Combine multiple lines into one line

2006-01-16 Thread John Doe
Andrej Kastrin am Montag, 16. Januar 2006 14.32:
> Hi all,
>
> I have the file, which looks like:
>
> *RECORD*
> *ID*
> 001
> *TITLE*
> Here is title number one.
> *ABSTRACT*
> First sentence of the abstract. Second sentence of the abstract...
> Second line of the abstract.
>
> *RECORD*
> *ID*
> 002
> *TITLE*
> Here is title number one.
> *ABSTRACT*
> First sentence of the abstract. Second sentence of the abstract...
> Second line of the abstract.
>
> Is there any simple way to transform this file to look like:
> *RECORD*
> *ID* 001
> *TITLE* Here is title number one.
> *ABSTRACT* First sentence of the abstract. Second sentence of the
> abstract. Second line of the abstract.
>
> Thanks in advance for any pointers or notes.
>
> Cheers, Andre

The following does what you want in a somehow generic way (except from the 
additional empty line at the very end), but it is more short than simple, and 
there must exist an easier regex I have not found:

use strict; use warnings;
local $/="";
while() {
  s/((?<=\*)|(?http://learn.perl.org/> 




Re: about the var's scope

2006-01-16 Thread John Doe
Shawn Corey am Montag, 16. Januar 2006 04.12:
[...]
> > 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'.

Hi again Shawn,

I have a question concerning the code presented in the OP. I repeat it for 
better overview:

 Version 1 
  script.pl:
  
  use vars qw($q);
  use CGI;
  use lib qw(.); 
  use My::HTML qw($q); # My/HTML.pm is in the same dir as script.pl
  use My::Doc  qw($q); # Ditto
  $q = new CGI;

  My::HTML::printmyheader();  
  
  My/HTML.pm
  
  package My::HTML;
  use strict;

  BEGIN {
use Exporter ();
@My::HTML::ISA = qw(Exporter);
@My::HTML::EXPORT  = qw();
@My::HTML::EXPORT_OK   = qw($q);
  }
  use vars qw($q);
  use My::Doc  qw($q);
  sub printmyheader{
# Whatever you want to do with $q... e.g.
print $q->header();
My::Doc::printtitle('Guide');
  }
  1;  
  
  My/Doc.pm
  
  package My::Doc;
  use strict;

  BEGIN {
use Exporter ();
@My::Doc::ISA = qw(Exporter);
@My::Doc::EXPORT  = qw();
@My::Doc::EXPORT_OK   = qw($q);
  }
  use vars qw($q);
  sub printtitle{
my $title = shift || 'None';
print $q->h1($title);
  }
  1;
 END Version 1

The code demonstrates the usage of the use vars pragma and the Exporter.

However, my personal feeling ist that in a bigger project it is eventually bad 
style to use globals this way?!?

Do you agree? Or do I  - again - overlook something?

See the equivalent code below as an alternative:

 Version 2 
  script.pl:
  
  use CGI;
  use lib qw(.); 
  use My::HTML;
  my $q = new CGI;

  My::HTML::printmyheader($q);  
  
  My/HTML.pm
  
  package My::HTML;
  use strict;

  use My::Doc;
  sub printmyheader{
   my $q=shift;
   ### DO CHECKS HERE
   # Whatever you want to do with $q... e.g.
   print $q->header();
   My::Doc::printtitle($q, 'Guide');
  }
  1;  
  
  My/Doc.pm
  
  package My::Doc;
  use strict;

  sub printtitle{
my $q=shift;
### DO CHECKS HERE
my $title = shift || 'None';
print $q->h1($title);
  }
  1;
 END Version 2

This version does the same, is shorter, is easier to understand for some 
people, does not require Exporter, and does not need use'ing My::Doc in the 
main script (it's more modular).

Does this 2nd version lack any features/magic present in the 1st?
(Apart from demonstrating use vars / Exporter of course)

Any comments are very appreciated!

greetings 
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: interpolation

2006-01-15 Thread John Doe
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

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: about the var's scope

2006-01-15 Thread John Doe
Shawn Corey am Montag, 16. Januar 2006 04.12:
> 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.

Shawn, Jeff,

seems that it couldn't be more embarassing/awqward for me...
(yes, I know who Stas Bekman is, Jeff)

On the other side, I'm very happy having demonstrated the mess in my brain 
with the last post, since, at last, I begin to realize now something that I 
had the feeling not to fully understand during several years (sic!). 

I fear the result was an unnecessary amount of complexity in a lot of my code 
that could have been avoided. Have to check that in detail.

> 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'.


Part of my confusion was (I think) that I didn't realize that, with 
$main::q = \*My::HTML::q,
I can not only "influence the main script by a module", but also in the other 
direction! (as the term 'alias' says...).

Now, I see the code in the OP with different eyes!

Thanks a *lot* to you two for giving me the chance to understand the 
use vars / Exporter issue better!

Arggg...

Have a nice time
joe

-- 
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 John Doe
[reordered to bottom style posting]
> -Original Message-
>
> >From: Shawn Corey <[EMAIL PROTECTED]>
> >Sent: Jan 15, 2006 10:58 PM
> >To: beginners@perl.org
> >Subject: Re: about the var's scope
> >
> >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
[...]

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

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: interpolation

2006-01-15 Thread John Doe
The Ghost am Freitag, 13. Januar 2006 21.23:
> I know I could do that, but what if I don't know the variable names
> in the string?
>
> > $sql=~s/\$Status/$Status/;
>
> could I do:
> $sql=~s/\$(\S+)/${$1}/;
>
> On Jan 10, 2006, at 5:57 PM, John Doe wrote:
> > The Ghost am Dienstag, 10. Januar 2006 21.57:
> >> I want to pull some text from a database:
> >>
> >> RxNumber in (select RxNumber FROM restoreReports WHERE Status in
> >> $Status)
> >>
> >> then I want perl to use this string and interpolate the variables
> >> ($Status).
> >>
> >> so:
> >>
> >> my $Status= "('New','Old')";
> >> my $sql=get_SQL_String(); #will get 'RxNumber in (select RxNumber
> >> FROM restoreReports WHERE Status in $Status)'
> >
> > $sql=~s/\$Status/$Status/;
> >
> > (first time as literal string, second time as perl variable defined
> > in the
> > surrounding context)
> >
> > see
> >
> > perldoc perlre
> >
> >> print $sql;
> >>
> >> # should print:
> >>
> >> RxNumber in (select RxNumber FROM restoreReports WHERE Status in
> >> ('New','Old'))
> >>
> >>
> >> What can I do?

Could you reformulate your (top posted) question?
What do you mean exactly by "not knowing the variable names in the string?"
- $Status (chars in the string) and/or 
- Status (mysql) and/or 
- $Status (in the perl code)?


-- 
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 John Doe
Jeff Pang am Samstag, 14. Januar 2006 12.52:
> Thanks for Adriano.I have tried the way that mentioned by you,and  found
> it's no use for me. should the '-F' option  have no effect for symlinks
> maybe?
>
> -Original Message-
>
> >From: Adriano Ferreira <[EMAIL PROTECTED]>
> >Sent: Jan 14, 2006 7:23 PM
> >To: Jeff Pang <[EMAIL PROTECTED]>, beginners@perl.org
> >Subject: Re: the 'tail' problem
> >
> >Jeff,
> >
> >Maybe all you have to do is make some adjustments to the pipe you're
> >opening. Besides the well known "-f" switch, some tail's (like gnu
> >tail) support "-F" which means a file is followed by its name and the
> >opening is retried from time to time. From "man tail" (GNU):
> >
> >   -F same as --follow=name --retry
> >
> >  With  --follow  (-f),  tail  defaults to following the file
> > descriptor, which means that even if a tail'ed file is renamed, tail will
> >  continue to  track  its  end.   This  default behavior is not desirable
> > when you really want to track the actual name of the file, not the file
> > descrip- tor (e.g., log rotation).  Use --follow=name in that case.  That
> > causes tail to track the named file by reopening it periodically to see
> > if  it has been removed and recreated by some other program.
> >
> >If you found it works for symlinks, all you have to do is use
> >
> >> open (TAIL,"tail -F $log|") or die "can't open pipe:$!";
> >
> >Regards,
> >Adriano Ferreira.
> >
> >On 1/14/06, Jeff Pang <[EMAIL PROTECTED]> wrote:
> >> I have a log file which is a symbol link to the real logfile,shown as
> >> following:
> >>
> >> 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:$!";
> >>
> >> 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:
> >
> >[snip]
> >
> >> How can I adjust this problem?Thanks a lot.

Hi

After reading man tail I tested

   tail --retry --follow=name testlog

where testlog is a symlink. While this command is running, I can do (from 
another console):

   rm testlog
   ln -s testlog1 testlog
   rm testlog
   ln -s testlog2 testlog

It does what you want.

Maybe File::Tail will also do what you want, just test it (and read the man)

hth
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Matching the first string

2006-01-13 Thread John Doe
[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...

alex,

use mgloland's version.

Thanks :-)

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Matching the first string

2006-01-12 Thread John Doe
alex litvak am Donnerstag, 12. Januar 2006 21.11:
> Hello all
> im new in perl and i need some help
>
> 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.

-- >>

use strict; use warnings;

$_='01 - Eminem Encore.mp3', /^[^a-zA-Z]*([a-zA-Z])/, print $1;

<< --

But first, read (at the cmdline):

perldoc perlre

where you can find most information on regular expressions to adjust the above 
one to your needs.

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Help with my thought process...parsing a log

2006-01-11 Thread John Doe
Robert Hicks am Mittwoch, 11. Januar 2006 17.00:
> "John Doe" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>
> > Robert Hicks am Dienstag, 10. Januar 2006 18.16:
> > > I have an application log that shows the "time", "id" and "type" for a
>
> user
>
> > > logging in. A short except looks like this:
> > >
> > > 19/12/2005 07:28:37  User (guest) logging in from (LIMS-CIT) - Assigned
> > > Userno (7045)
> > > 19/12/2005 07:32:06  User (guest) logging in from (LIMS-CIT) - Assigned
> > > Userno (1959)
> > > 19/12/2005 07:51:38  User (guest) logging in from (LIMS-CIT) - Assigned
> > > Userno (7601)
> > > 19/12/2005 07:54:10  User (guest) logging off - Userno (7601)

The structure of the logoff line differs from the login line.

> > Are you interested in one specific Userno only, or do you want the login
> > times for all Usernos?
> >
> > What do you mean by "could log in and log out multiple times"? In
> > parallel, or sequential? If parallel: Are different Usernos assigned 
> > for the same user logged in multiple times?
>
> I am not really interested in the "user" per se just the "Userno" but that
> can appear several times in the log
> for both logins and logouts.
>
> So I need to first find the login line and Userno and then find the first
> logout line with the Userno and then
> do a time diff.

[...]

> I have only created a regex so far to split the information out and doing
> some counts. Code is below:
>
> use strict;
> use warnings;
> use English;
> use Carp;
>
> my $filename = 'test.log';
> open my $LOG, '<', $filename or croak "Can't open '$filename': $OS_ERROR";
>
> # Test line from logfile
> #$_ = "19/12/2005 08:53:31 ECP3.2.01.1008I : User (guest) logging in from
> (LIMS-CIT) - Assigned Userno (A50C)";
>
> # This parses a login entry
> while (<$LOG>) {
>
> my ( $date, $time, $ecp, $login_message, $login_type, $login_loc,
> $userno,
> $userid )
> = / # regex begins
> ^   # string anchor
> (\d{2}.\d{2}.\d{4}) # $date
> \   # literal space
> (\d+:\d+:\d+)   # $time
> \   # literal space
> (ECP\d.\d.\d{2}.\w{5})  # $ecp
> \   # literal space
>
> :   # literal :
>
> \   # literal space
> (User\s\([\S.]+\))  # $login_message
> \   # literal space
> (logging\sin)   # $login_type
> \   # literal space
> (from\s\([\S.]+\))  # $login_loc
> \   # literal space
> -   # literal -
> \   # literal space
> (Assigned\sUserno)  # $userno
> \   # literal space
> \(  # literal (
> (\w{4}) # $userid
> \)  # literal )
> /xms;   # regex ends
>
> print join "\n", $date, $time, $ecp, $login_message, $login_type,
> $login_loc, $userno, $userid, "\n";
> last;  # I only want one line returned from the log for testing
> }
>
> This prints out:
>
> 19/12/2005
> 07:28:37
> ECP3.2.01.1008I
> User (guest)
> logging in
> from (LIMS-CIT)
> Assigned Userno
> 7045

Ok, one way is to extract the information by regexes (for two different line 
structures). Another one I choose below is split. I omit the strings that are 
always the same, like "loggin in", and some others for brevity.

It's just a skeleton you could start with:

 begin script 

#!/usr/bin/perl

use strict;
use warnings;

sub diff {'exercise for the reader: '.join ', ', @_};

# key: userno
# value arrayref with five entries: 
# login date and time, logoff date and time, calculated time diff
#
my %table;

while () {
  my @fields=split /\s+/, $_;
  my ($date, $time, $inout, $userno)=(@fields[0,1,5], 0);

  if ($inout eq 'in') {
($userno)=$fields[11]=~/\((.+)\)/;
if (exists $table{$userno}) { warn "$userno already logged in";}
else { $table{$userno}=[$date, $time]; }
  }
  else {
($userno)=$fields[8]=~/\((.+)\)/;
unless (exists $table{$userno}) { warn "$userno not logged in";}
else {
  my $time_diff=diff(@{$table{$userno}}, $date, $time);
  print "$userno: $time_diff\

Re: interpolation

2006-01-10 Thread John Doe
The Ghost am Dienstag, 10. Januar 2006 21.57:
> I want to pull some text from a database:
>
> RxNumber in (select RxNumber FROM restoreReports WHERE Status in
> $Status)
>
> then I want perl to use this string and interpolate the variables
> ($Status).
>
> so:
>
> my $Status= "('New','Old')";
> my $sql=get_SQL_String(); #will get 'RxNumber in (select RxNumber
> FROM restoreReports WHERE Status in $Status)'

$sql=~s/\$Status/$Status/;

(first time as literal string, second time as perl variable defined in the 
surrounding context)

see

perldoc perlre

> print $sql;
>
> # should print:
>
> RxNumber in (select RxNumber FROM restoreReports WHERE Status in
> ('New','Old'))
>
>
> What can I do?

hth,
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: string interpolation when reading from a file

2006-01-10 Thread John Doe
Dan Huston am Dienstag, 10. Januar 2006 21.40:
> Greetings --
>
> I am reading text sql commands) from a file, chopping it into sections
> and then writing each section out to a different file. Within the text
> are perl variables that I had expected to be interpolated as they were
> written out to the new file but they are not.
>
> Here is a sample line:
>
> REVOKE SELECT ON $TABLE_NAME FROM PUBLIC;
>
> $TABLE_NAME for example might be 'STUDENTS'.
>
> Is there a reason that the text is not being interpolated when before it
> is written out to the new file (either when it is read in or when it is
> printed out)?
>
> Here is a piece of my code:
>
>
> ##CODE SNIPPET   #
>
> for $k ( @these_lines ) {
>
> # for debugging
> print "$TABLE_NAME\n";
> print "K\t=>\t$k\n";
>
> ### SQL_OUT is the filehandle that I am writing to
> print SQL_OUT "$k\n";

$k _itself_ is interpolated into the double quoted string: $k contains a 
string with content looking like perl vars, $k is replaced by this string. 

But there is - luckily! - no second level interpolation included (the 
variable names _in_ the string _in_ variable $k).

You would have to make the second level interpolation explicit

   my $var='hi!';
   print eval "q(He said $var and disappeared)";
=>He said hi! and disappeared

but this is DANGEROUS since the text could contain code instead of simple 
variable names.

There may be a useful templating module on search.cpan.org.

Or you could reinvent the wheel and parse for the variable names and replace 
them with values. Something along the lines

use strict; 
use warnings;
my %vars=(TABLE_NAME=>'STUDENTS');
my @these_lines=('REVOKE SELECT ON $TABLE_NAME FROM PUBLIC $UNKNOWN;');
for (@these_lines) {
s/\$([_a-zA-Z]\w*)/$vars{$1} || '$'.$1/eg;
}
print @these_lines;

>
> } ### CLOSE-FOR-K
>
>
> produces this output in STDOUT:
>
> TABLE_NAME  =>  STUDENTS
> K   =>   REVOKE SELECT ON $TABLE_NAME FROM PUBLIC;
>
> where I want to have :
>
> K   =>   REVOKE SELECT ON STUDENTS FROM PUBLIC;
>
>
> ##CODE SNIPPET   #
>
>
> Thanks
> Dan

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Add comment to a pattern matched file line

2006-01-10 Thread John Doe
Vincent Li am Dienstag, 10. Januar 2006 19.59:
> Hi List:

Hi Vincent

> I have two files like this:
>
> file1:
> score CN_SUBJ_PROMOTE3.100 # [0.000..3.100]
> score CN_SUBJ_PROMOTION  3.600 # [0.000..3.600]
> score CN_SUBJ_PROVIDE3.000 # [0.000..3.000]
>
> file2:
> CN_SUBJ_PROMOTE
> CN_SUBJ_PROMOTION
>
> If string CN_SUBJ_PROMOTE exist in file2 and file1, add comment (#) to
> file1 like:
>
> #score CN_SUBJ_PROMOTE3.100 # [0.000..3.100]
> #score CN_SUBJ_PROMOTION  3.600 #[0.000..3.600]
>
> I came  up with this script:

Which is not easy to test, so I didn't :-)

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

Great two lines!

> use Tie::File;
>
> tie my @array1, ,'Tie::File',  "file1" or die "Could not tie file1!";
> tie my @array2, ,'Tie::File',  "file2" or die "Could not tie file2!";
>
> for (@array2) {
> my $string = $_;

shorter: for my $string (@array2) {

>for (@array1) {
>if (/$string/) {
> s/$_/#$_/;

Eventually it is faster just to handle the beginning of the line 
with s/^./#./

> }
> }
> }
>
> It did not work as I wish, any thoughts or other method to do this?

How did it not work as expected?

You pass through the whole @array1 for every value in @array2, this is much 
work. If the lines in file1 are unique and not very numerous, you could use a 
hash (line_content=>line_number) instead of @array1, modify it and write it 
back to file at the end. In this case, a substitution would not be necessary,  
'#' could simply be prepended (i _think_ this is faster than a subst).

There may also be a useful module on search.cpan.org.

hth, 
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Understanding Benchmark results

2006-01-10 Thread John Doe
Steve Bertrand am Dienstag, 10. Januar 2006 18.24:
> Hi all,

Hi Steve

> I've a project on the go, where I must compare a single field of more
> than 3 million database records, then sort them largest to smallest. The
> field will contain up to a 6 digit integer.

(I think you must have a reason not to sort the values while retrieving them 
from the database - or is it not a SQL db?)

> Just to ensure the most efficient possible run, I've been doing tests
> with benchmark.
>
> I'll post the relevant code, then the results. What I want to know is
> the cmpthese() results. I *think* that 'b' is much more efficient than
> 'a'. My assumption is that 'b' 

you mean: 'a'

> can perform 79531 operations per second, 
> where 'b' is only doing 20666. Am I looking at this right? Is the
> Schwartzian Transform really about 300% better than just plain sort?

No, about 300% more _slowly_, since 'a' is doing more per second than 'b'.

This seems also plausible from the fact that the schwarzian transformation in 
'b' does a comparison like 'a' does, but does additional work.

>  code snip (and yes -w and strict are in effect :) 
>
> if ($benchTest) {
>
> my $r1 = sub {
> my @unsorted = qw(3 4 9 88 24 1034 28);
>
> my @sorted = sort {$a <=> $b} @unsorted;
> };
>
> my $r2 = sub {
> my @unsorted = qw(3 4 9 88 24 1034 28);
>
> my @sorted =
> map $_->[0],
> sort { $a->[1] <=> $b->[1] }
> map [ $_, $_ ],
> @unsorted;
> };
>
> my $href = { 'a' => $r1, 'b' => $r2, };
> my $result = timethese(-10, $href);
> cmpthese($result);
>
> }
>
> - results ---
>
> Benchmark: running a, b, each for at least 10 CPU seconds...
>  a: 11 wallclock secs (10.59 usr +  0.01 sys = 10.60 CPU) @
> 79531.20/s (n=843155)
>  b: 11 wallclock secs (10.44 usr +  0.02 sys = 10.45 CPU) @
> 20665.69/s (n=216021)
>
>  Rateba
> b 20666/s   -- -74%

read: b performs 74% compared with a.

> a 79531/s 285%   --

hth, 
joe

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Help with my thought process...parsing a log

2006-01-10 Thread John Doe
Robert Hicks am Dienstag, 10. Januar 2006 18.16:
> I have an application log that shows the "time", "id" and "type" for a user
> logging in. A short except looks like this:
>
> 19/12/2005 07:28:37  User (guest) logging in from (LIMS-CIT) - Assigned
> Userno (7045)
> 19/12/2005 07:32:06  User (guest) logging in from (LIMS-CIT) - Assigned
> Userno (1959)
> 19/12/2005 07:51:38  User (guest) logging in from (LIMS-CIT) - Assigned
> Userno (7601)
> 19/12/2005 07:54:10  User (guest) logging off - Userno (7601)
>
> I need to get the difference in the time from when 7601 logged into the
> system and logged out of the system. The caveat is that 7601 could log in
> and log out multiple times. I am having a hard time thinking about how to
> do that.
>
> Should I find the first login and look for the logout, get the diff and
> reset some counter. Do I use a hash for this?
>
> Just a little push (not off the cliff please)...is all I need.

Are you interested in one specific Userno only, or do you want the login times 
for all Usernos?

What do you mean by "could log in and log out multiple times"? In parallel, or 
sequential? If parallel: Are different Usernos assigned for the same user 
logged in multiple times?

A hash (or hash of hashes / hash of arrays) could be useful to lookup Usernos 
or login times.

Have you some code to post, f.e. the part extracting the wanted info from the 
lines?

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Byte array

2006-01-10 Thread John Doe
John Doe am Dienstag, 10. Januar 2006 15.06:
> [EMAIL PROTECTED] am Dienstag, 10. Januar 2006 14.08:
> > 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.
>
> Don't forget to put
>
>   use warnings;
>   use strict;
>
[...]

> > John:
> > 
> > Thanks very much.  That did the trick, except I get tons of errors when I
> > include "use strict" like:
> > 
> > Global symbol "$totalNumPkts" requires explicit package name at
> > sibtest1.pl 
> > line 9.

yes, that is because of the usage of undeclared variables. Simply define your 
variables with my, see

perldoc -f my

and, related, the other ways of declaring variables:

perldoc -f our
perldoc vars

The usage of 'use strict' and declaring variables may look as "too much work", 
but it will help *a lot* in finding errors, even subtle ones. Not to speak 
from bigger projects :-)

Best thing to do it always, even in 10 line scripts :-)

> > But, it now sends the message size I wanted.  I have been using O'Reilly's
> > "Learning Perl" but it seems not to address everything.  Do you have
> > another reference that you think is better?  Thanks again.

"Learning Perl" is a good book, but it's intention is to teach the basics; the 
example are as short as possible to demonstrate something - nearly everything 
needed *in practice* is omittet, input sanitizing as an example.

Good sources are f.e:

- this list, or perlmonks.org, or any other place where realistic examples are 
discussed
- the source code of standard perl modules
- further perl code on cpan.org
- ...

With the time, you will know the people that are known to write good (open 
source) code.

greetings, joe

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




  1   2   3   4   >