Re: A multi line pattern match question

2016-07-14 Thread Charles DeRykus
One easier approach:

use Tie::File;
tie( my @array, 'Tie::File', "/path/to/file" )
   or die $!;

my $n = 0;
while ( $n <= $#array )  {
  if ( $array[$n] =~ /.*[Oo]rder deny,allow(.*)/  and
$n < $#array and $array[$n+1] =~ /[\Dd]eny from all(.*)/ )
  {
  $n += 2 and print "\tRequire all denied\n";
  next;
  }
  print $array[$n++],"\n";
}



On Thu, Jul 14, 2016 at 7:50 AM, Darryl Philip Baker
 wrote:
> While not truly a beginner it feels that way after not doing anything 
> substantial in Perl in many years.
>
> I currently need a program to take Apache HTTPD configuration files in HTTPD 
> 2.2 syntax used in current production and convert them to HTTPD 2.4 syntax in 
> future production. I will need to do this many times weekly until we cut over 
> to the new systems. My first challenge is converting the permissions syntax:
> Order deny,allow
> Deny from all
> To
> Require all denied
> And similar transformations. I was able to make this modification if I set $/ 
> = undef and look at the file as a whole. My problem is I really want to 
> process the file line by line to remove several  ... 
>  blocks which may have other conditional code blocks contained 
> within them. I have considered using two separate scripts and a two pass 
> solution but there is a part of me which would rather have a single script do 
> it all in one pass.
>
> My current attempt, after several tries, is:
>  if ( m/{.*}[Oo]rder deny,allow(.*)\n(.*)[Dd]eny from all(.*)/) {
> print "\tRequire all denied\n";
> next;
> }
> While not causing syntax errors it is not doing what I want either. I am 
> probably using the 'm/' incorrectly and need your help.
>
> Darryl Baker
>
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>
>

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: unexpected escaping

2016-01-29 Thread Charles DeRykus
On Fri, Jan 29, 2016 at 12:39 AM, Jorge Almeida  wrote:
> Can someone help me to understand this?
>
> #!/usr/bin/perl
> use strict;
> use warnings;
> my $s='\\n';
> print $s;
>
>
> Output:
> \n
>
> Expected output:
> \\n
>
>
> Jorge Almeida
>


From: perldoc perlop

 q/STRING/
   'STRING'
   A single-quoted, literal string.  A backslash represents a
   backslash unless followed by the delimiter or another backslash, in
   which case the delimiter or backslash is interpolated

so, you'll need: my $s = 'n'

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: access hash in specific sequence

2015-09-03 Thread Charles DeRykus
On Thu, Sep 3, 2015 at 9:42 AM, Gary Stainburn
 wrote:
> I have a hash of hashes which I converted to an array of hashes because I
> needed to access them in a specific sequence.  It now looks like
>
> my @pagetypes=(
> {'pagetype'=>'Delivery  Note','weight'=>2,.
> {'pagetype'=>'Sales Invoice','weight'=>2,.
> {'pagetype'=>'Purchase Invoice','weight'=>2,.
> ..
>
> I then access the array using
>
> foreach my $pt (@pagetypes) {
>
>
> However, I have now lost the ability to access each pagetype by it's name
>
> I am aware that you cannot define a key sequence when defining a hash.
> However, if I create a sequence field
>
> my %pagetypes=(
> 'Delivery  Note'=>{'seq'=>1,weight'=>2,.
> 'Sales Invoice'=>{'seq'=>2,'weight'=>2,.
> 'Purchase Invoice'=>{'seq'=>3,'weight'=>2,.
> ..
>
> How can I do the foreach statement to access them in the correct sequence?
>

If the 'seq' items just maintain insertion order, then:

use Tie::IxHash;
use feature 'say';

tie( my %pagetypes, 'Tie::IxHash') or die $!;
%pagetypes=( 'Delivery Note' => ...,  Foo=>, Bar=>);

foreach my $pagetype (keys %pagetypes) { ... }
say $pagetypes{'Delivery  Note'}{weight};

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Display a hash in the order of an array

2015-07-20 Thread Charles DeRykus
On Mon, Jul 20, 2015 at 6:19 AM, Vincent Lequertier  wrote:
> Thank you for the help, Charles! Unfortunately, I'm not able to figure out
> how to access the element of %ordered, despite some diggings in the perldoc
> (http://perldoc.perl.org/perldsc.html).
> I can print a single element with print
> $ordered{'xxx.xxx.xxx.xxx'}[0]{'[15/Jul/2015:10:30:03 +0200]'}{action};
>
> But I don't find how to get the dates e.g. '[15/Jul/2015:10:30:03 +0200]'
>
> Here is what I've tried:
>
> tie( my %ordered, 'Tie::IxHash', map { ( $_,[ ] ) }   @ip );
>
> while ( my($key,$value) = each %hash ) {
> push @{$ordered{$value->{ip}}}, {$key, $value};
> }
> #print Dumper \%ordered;
> my $i = 1;
> for my $key (keys %ordered) {
> print "ip number $i : $key\n";
> for my $entry (@{$ordered{$key}}) {
> print $entry . "\n";
> }
> ++$i;
> }
>

Depending on output preference and level of detail, one possibility:

...
   for  foreach my $entry ( @{$ordered{$ip}} ) {
while ( my($date, $data) = each %{$entry} ) {
  say join( " ","$date:", $data->{ip}, $data->{action} );
}
   }

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Display a hash in the order of an array

2015-07-17 Thread Charles DeRykus
Another approach using Tie::IxHash:

use Tie::IxHash;
use Data::Dumper;
use feature 'say';

my @ip = (...)
my %hash = (...);

tie( my %ordered, 'Tie::IxHash', map { ( $_,[ ] ) }   @ip );

while ( my($key,$value) = each %hash ) {
push @{$ordered{$value->{ip}}}, {$key,$value};
}
say Dumper \%ordered;

Leaving exact details of printing as an exercise for reader...

--
Charles DeRykus

On Fri, Jul 17, 2015 at 6:11 AM, Vincent Lequertier  wrote:
> Hi,
>
> I have the following structure :
>
> $hash{$date} = {
> 'ip' => $ip,
> 'action'   => $action,
> };
>
> witch produce data like :
>
> $VAR1 = '[15/Jul/2015:10:30:03 +0200]';
> $VAR2 = {
>   'ip' => 'xxx.xxx.xxx.xxx',
>   'action' => 'GET xxx'
> };
>
> and an array of ip addresses, say @ip
>
> My question is how can I display the content of %hash in the order of @ip,
> assuming %hash has the same length as @ip ?
>
> Thank you
>
> --
> Vincent Lequertier
> vincentlequertier.tk
>
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>
>

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Debugging and passing constant value at run time

2015-07-07 Thread Charles DeRykus
On Tue, 7 Jul 2015 11:40:35 +
"Sharanbasappa Raghapur, ERS, HCLTech"  wrote:

> I am using constant mainly to enable printing of debugging messages
> (e.g. use constant DEBUGGING_L1 => 0;) Normally, the value is '0' and
> when I need to see debug messages, I make this 1 and run the script.
>
> Is there a way to allocate value to constants at run time so that I
> can avoid editing the script again and again? Also, is there a better
> way to handle debugging?

You don't get those conditional compilation speedup's
but you could pass an argument to the script to save
editing:


#!perl
my $DEBUG;
($DEBUG = shift) //= 0;  # no debug if no arg missing
...

if ($DEBUG) { ... }

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: catching utf8 errors

2015-03-14 Thread Charles DeRykus
On Sat, Mar 14, 2015 at 2:38 AM, Manfred Lotz  wrote:
> Hi all,
> I wanted to test what happens if Perl encounters an error when reading
> a utf8 encoded file.
>
> Here a minimal example:
>
> #! /usr/bin/perl
>
> use strict;
> use warnings;
>
> my $fname = $ARGV[0];
>
> open my $fh, '<:encoding(UTF-8)', $fname
>   or die "Couldn't open file: $fname";
>
> my $string = <$fh>;
> close $fh;
>
> print "Reaching the end\n";
>
>
> Running it on a file where I had inserted a hex \x90 gives the
> following error message which is fine.
>
> utf8 "\x90" does not map to Unicode at ./read_utf8.pl line 11.
> Reaching the end
>
>
> Question: The error above goes to stderr which basically is ok.
> Hovever, I want to take action in my script if such an error occurs. How
> do I notice it programmatically?
>
>

open my $fh, '<:encoding ) or die ...

{  open( local *STDERR,'>',\my $err);
   my $string = <$fh>;
if ($err =~ /does not map to Unicode/) {
# take action.
 }
}


-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: An issue of Scope that I do not understand

2015-02-28 Thread Charles DeRykus
> ...
>
> I'm not sure why you don't just pass $task as an argument to the
> report_xxx subs...?
>
> A closure (perldoc -q closure)  would be the long way around unless
> I've missed something:
>
> my $task;
> my $iter;
> my $report_static = sub { my $ref = shift;
>  print  $ref->[$iter++];
>   
> };
>
> my $report_dynamic = sub( my $ref = shift;
>print $ref->[$iter++];
>...
>
> #MAIN_CODE START
> 
> foreach $task (@tasks) {
>  if (  )
>$report_static->(\@tasks);
>...
>  else
> $report_dynamic->(\@tasks);
>...
>  }
> }
>
>

You could also simplify the closure  since @tasks is in the closure's
lexical scope, eg,

my $report_static = sub {   print $tasks[$iter++]; ... };

foreach $task (@tasks) {
  if (...)
  $report_statics->();
  else
  $report_dynamic->();
  ...
}

But with everything in lexical scope, you could just  pass any needed
arg's directly and
eliminate the closure altogether.


-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: An issue of Scope that I do not understand

2015-02-27 Thread Charles DeRykus
On Fri, Feb 27, 2015 at 8:24 PM, Martin G. McCormick
 wrote:
> Brock Wilcox writes:
>> I'm afraid a bit more context is needed to identify the problem. Could you
>> post your entire bit of code into a gist or pastebin or something for us
>> to
>> see?
>
> I'll do better than that. This is a script which is
> stripped of everything but the problem code. It is 20 lines long
> and here it is.
>
> #!/usr/bin/perl -w
> use strict;
>
> #Declare main variables.
>
> #main locals
> my @tasks;
> my $task;
> my $report_static;
> $report_static = sub {
> print "$task\n";
> };
>
> #MAIN_CODE START
> $tasks[0] = "red";
> $tasks[1] = "blue";
> $tasks[2] = "green";
> foreach $task (@tasks) {
> &$report_static;
> }
>

I'm not sure why you don't just pass $task as an argument to the
report_xxx subs...?

A closure (perldoc -q closure)  would be the long way around unless
I've missed something:

my $task;
my $iter;
my $report_static = sub { my $ref = shift;
 print  $ref->[$iter++];
  
};

my $report_dynamic = sub( my $ref = shift;
   print $ref->[$iter++];
   ...

#MAIN_CODE START

foreach $task (@tasks) {
 if (  )
   $report_static->(\@tasks);
   ...
 else
$report_dynamic->(\@tasks);
   ...
 }
}

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Debug when script WILL NOT RUN

2015-02-01 Thread Charles DeRykus
On Sat, Jan 31, 2015 at 1:58 PM, Harry Putnam  wrote:
> I've given myself a headache googling on how to debug a perl script
> that does not run.
>
> Maybe `debug' is the wrong word... I'd love to know if there is a more
> accurage one.
>
> I realize this post is quite a lot of yak, but hoping someone can lay
> out a few steps that will narrow down the problem.
>
> Many, many of the google hits are all about using the debugger, which
> of course is a non-starter if the darn script will not run due to
> compilation errors..
>
> I have about 100 lines or so inside a File::Find:
>
>   find (
>  sub {
>  }, $tdir;
>);
>
> Type of setup. I've beat down the multitudiness errors that perl found
> during compilation.  Down to the last one I'm getting.
>
> Before posting all the boring, poorly written code, I thought I'd ask if 
> people
> here can outline a few things to do in a case like this.
>
> So far, after getting down to this complilation error:
>
>   syntax error at ./t line 96, near "$tdir;"
>   Execution of ./t aborted due to compilation errors.
>
> I've gone thru the lines trying to find what is causing the
> error but of course am overlooking it.
>
> Then I pulled just the find(...) part out, put it in its own file.. no
> bang line or nothing and just ran it like: ` perl myscript'.
>
> The error above was the result.
>
> So, how to start breaking down the code to find the problem?
>
> On the surface I can not see a syntactical error at that line.
>
> which looks like this ... snipped:
>
>  [...]
>
>   }<==  incloses an if clause
> }  <==  incloses a while loop
> close $fh;
>   }, $tdir;<==  inclusing subroutine
>);
>
>

One good sleuthing tool is perltidy (perltidy.sourceforge.net) which is good
at unraveling a rat's nest of errors to  tease out the culprit:

For instance, you'd run: perltidy badlywrittenscript.pl and might get
an error diagnostic file that'd say something like:

  The most recent un-matched '{' is on line 7
   7: for my $i (@xxx) {
  ^
   12: To save a full .LOG file rerun with -g

---
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: should this old forumulation still work?

2015-01-20 Thread Charles DeRykus
On Tue, Jan 20, 2015 at 9:12 PM, Uri Guttman  wrote:
> On 01/20/2015 11:28 PM, Charles DeRykus wrote:
>>>
>>> ...
>>>   or something odd
>>>my $contents = do { local $/; map { chomp }  };
>>>
>> I'm afraid this, while appealing,  in my testing generates an
>> incorrect result, ie,  1.
>>
>> 
>> What happens I suspect is that the map{ } is in void context, not the
>> scalar context of the outer do{}.  Remember parsers are not as
>> all-knowing as we'd like them to be. Therefore map churns merrily
>> along and  tosses its intermediate results  until the final line.
>> Only at that point does parser wake up and say "Aha, the do{ } wants
>> scalar context so my final map{} value needs
>> to be returned in scalar context.  So here's what  map{} does in
>> scalar context. From 'perldoc -f map' :
>
>
> the map call is in scalar, not void context. the do block returns the value
> of the last statement and that is being assigned to a scalar. context is
> propogated in (like with subs) so map is in scalar context. regardless,
> using map with no return value is never a good idea as it subverts its
> purpose and misleads the reader of the code.
>

Yes, I understand.  I was speculating more about when the propagation occurred,
i.e, early or late. By "void" context, I erred and meant that the
actual map results
were themselves tossed into the "void". Only the count mattered.

Clearly though, the chomp occurs only on a single string anyway due to
the $/ setting
so it's not the intended result..

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: should this old forumulation still work?

2015-01-20 Thread Charles DeRykus
> ...
>  or something odd
>   my $contents = do { local $/; map { chomp }  };
>

I'm afraid this, while appealing,  in my testing generates an
incorrect result, ie,  1.


What happens I suspect is that the map{ } is in void context, not the
scalar context of the outer do{}.  Remember parsers are not as
all-knowing as we'd like them to be. Therefore map churns merrily
along and  tosses its intermediate results  until the final line.
Only at that point does parser wake up and say "Aha, the do{ } wants
scalar context so my final map{} value needs
to be returned in scalar context.  So here's what  map{} does in
scalar context. From 'perldoc -f map' :

 In scalar context,
   returns the total number of elements so generated.  Evaluates
   BLOCK or EXPR in list context, so each element of LIST may
   produce zero, one, or more elements in the returned value.

Remember, map has tossed all but the final value at this point so it
just returns 1.

Clear as mud?



-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Looping regexes against a list

2015-01-20 Thread Charles DeRykus
On Tue, Jan 20, 2015 at 9:47 AM, Mike Martin  wrote:
> Thanks for the idea about qr, I did try this before, but I've now relooked
> at at it and got about 75% improvement.
>
> As regards the uninitialized point the errors were coming from regexes
> (different ones) when the regex wasnt matching, so testing the result of
> each regex match was not really an option. As an aside the source is really
> horrible - job ad listings.
>
> Basically the idea is
>
> Take a load of Job Vacancy posts (xml files - loads of)
> Parse the Information, getting rid of as much garbage as possible
> Push a distinct list into a lookup hash
> Do replace to this list against a long list of regexes
> Spit out nicely formatted Clean Job Titles
>
>
>
 Since qr was that significant, you don't have a static regex and there may well
be other improvements.  You might want to demo the list of regexes for the
shooting gallery :)

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Parsing multi column files

2015-01-18 Thread Charles DeRykus
On Sun, Jan 18, 2015 at 4:00 PM, Mike  wrote:
> So I've got a text file in a multi column format (three columns), each
> column is separated by a single space. Here is a snippet for reference:
>
> artless base-court apple-john
> bawdy bat-fowling baggage
> beslubbering beef-witted barnacle
>
> I want to be able to randomly select a word from the first column, then from
> the second column, then from the third column, and concatenate them to
> together into a single string. Here's the code I currently have, but I'm
> stuck:
>
> sub gen_ins {
> open(FH, '<', 'insults2.txt') or die "[-] ERROR: Can't find insult
> list.";
> my @cols = split (" ", );
> print "$cols[0]";
> close FH;
> }
>
> gen_ins();
>
> When currently run, gen_ins() will print out the first word of the given
> column: $cols[0], $cols[1], or $cols[2]. How can I access the rest of the
> words below the first?
>

'perldoc -f split'  and look at the 2nd argument. It's a string. What
you've written
internally becomes  split(" ", $_=).  Remember 'context'?  It's in play here
too because that'll just pick up the first line of the file. See:
perldoc perldata.

Actually,  you could do this until you grasp what's happening:

open(F,"rationale.txt")  or die $!;
my @lines = ;
my $line = $lines[ int(rand( $#lines ) ) ];  # perldoc -f rand
my @words = split(" ",$line) ;
say $words[0];

Then, if you're counting calories and want a one-liner:

perl -E 'open(F,"rationale.txt");@l=; say +( split(" ",
$l[int(rand($#l))]) )[0]'

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Using regular expressions to populate a variable?

2015-01-18 Thread Charles DeRykus
On Sun, Jan 18, 2015 at 9:28 AM, Jim Gibson  wrote:
>
>> On Jan 18, 2015, at 9:03 AM, Mike  wrote:
>>
>> I was able to find match extraction in the perldoc.
>>
>> Here is a snippet of what I have.
>>
>> my $insult = ( $mech->text =~ m/Insulter\ (.*)\ Taken/ );
>> print "$insult\n";
>>
>> But $insult is being populated with: 1
>>
>> It should be populated with text. Can anyone tell me what I'm doing wrong 
>> here?
>
> Your error is assigning the return value of the regular expression in a 
> scalar context. In scalar context, a regular expression returns true or false 
> indicating a match (or not). In array context, however, it returns the 
> captured subexpressions as a list.
>
> Try forcing the assignment into array context:
>
>  my( $insult ) = ( $mech->text =~ m/Insulter\ (.*)\ Taken/ );
> ...

For more info: see perldoc perldata.  There a full discussion of  list
vs scalar context .

-- 
Charles DeRykus

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: How does opendir/readdir process files

2015-01-13 Thread Charles DeRykus
> ...
> I think the normal and original behavior is no reference. I think
> they added the reference in 5.14 too. Perhaps the documentation
> just fails to mention that support for arrays was added in 5.14
> along with references? Hopefully I got that right this time. :)
>

Ah, RTFM would've helped ...  I  didn't slurp  the whole 'perldoc -f each' doc.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: How does opendir/readdir process files

2015-01-09 Thread Charles DeRykus
On Fri, Jan 9, 2015 at 10:31 AM, Brandon McCaig  wrote:
> Charles:
>
> On Fri, Jan 9, 2015 at 12:46 PM, Charles DeRykus  wrote:
>> On Fri, Jan 9, 2015 at 3:39 AM, Dermot  wrote:
>>> I think John has answered your immediate question.
>>>
>>> ...
>>> for (0..$#files) {
>>> print "$_) $files[$_]\n";
>>> }
>>>
>>
>> Alternatively (at least since 5.14) :
>>
>>
>> say "$k) $v" while ($k,$v) = each @files;
>
> perldoc -f each said:
> *snip*
>> When called in list context, returns a 2-element list
>> consisting of the key and value for the next element of a hash,
>> or the index and value for the next element of an array, so
>> that you can iterate over it.
> *snip*
>> Starting with Perl 5.14, "each" can take a scalar EXPR, which
>> must hold reference to an unblessed hash or array.  The
>> argument will be dereferenced automatically.  This aspect of
>> "each" is considered highly experimental.  The exact behaviour
>> may change in a future version of Perl.
>>
>> while (($key,$value) = each $hashref) { ... }
>>
>> See also "keys", "values", and "sort".
>
> Your usage should not depend on 5.14.
>
> Starting with 5.14, the EXPR passed to each() can be a reference to an
> array or hash instead of the data structure themselves, which will be
> automatically dereferenced. I believe that is the only bit of the
> functionality that is dependent on Perl 5.14 (and as of 5.14, the
> automatic dereference was considered experimental; my Cygwin
> environment is still back on 5.14..).
>

Definitely  needs  a 'use 5.014' if you want to dabble.

I had forgotten that it was experimental although, since it's been
available for some time,  I suspect it will follow the regex embedded
code pathway to legitimacy, "in use for years
before they dropped the 'experimental'  ".

Apparently undocumented that you don't need a reference either since
while(($key,$value) = each @array  works as well as 'each \@array'.

-- 
Charles

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: How does opendir/readdir process files

2015-01-09 Thread Charles DeRykus
On Fri, Jan 9, 2015 at 3:39 AM, Dermot  wrote:
> I think John has answered your immediate question.
>
> ...
> for (0..$#files) {
> print "$_) $files[$_]\n";
> }
>

Alternatively (at least since 5.14) :


say "$k) $v" while ($k,$v) = each @files;

--
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Get return value when running cmd like this

2015-01-05 Thread Charles DeRykus
On Mon, Jan 5, 2015 at 3:20 PM, Harry Putnam  wrote:
> When running  shell commands from perl script with an open() instead of
> system() or exec how is the return value snagged.
>
> I guess, if it doesn't die, it worked but how to snag that information
> and at what point?
>
> --- 8< snip -- 8< snip -- 8 #!/usr/local/bin/perl
>
> use strict;
> use warnings;
>
> my $log = '/home/harry/some.log';
> my $cmd = 'rsnapshot -c rsnap_Home.conf hourly';
>
> open my $fh, '>', "$log" or die
>   "Can't open $log: $!";
>
> open my $ch, '-|', "$cmd" or die
>   "Can't run $cmd: $!";
>
> while (<$ch>) {
>   print;
>   print $fh;
> }
>
> close $fh;
> close $ch;
>

By "snag that information" , do you mean the shell program's output ?
Did the 'open' appear to succeed but without generating any output
from your read loop? Does the read loop hang?

If not,  checking the close status as previously shown may reveal the
problem. But if your read loop hangs and there's no output,  the shell
process itself may be hanging for
some reason.   IPC::Open3 or the more versatile IPC::Run  might provide some
info about what was going on prior to the hang if the info isn't buffered:

use IPC::Run qw/run/;

my @cmd =("rsnapshot");
run( \@cmd,  \undef, \$out, \$err) or die "run: $!";
say "out:$out \nerr:$err"'

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Match HTML ...... string over multiple

2014-11-18 Thread Charles DeRykus
On Tue, Nov 18, 2014 at 12:22 PM, mimic...@gmail.com  wrote:
> I am trying to extract a table (.. until
> ) and its content from an HTML file.
>
> With the file I have something like this
>
> 
>  title="Product ">
> .
> .
> .
> 
> 
>
> There could be more that one table in the file.however I am only interested
> in the table within  .
>
> /^.*.+?( border="0".+?\s+<\/table>)\s*<\/div>.*$/ims
>
> The above and various variations I tried do not much.
>
> I am able to easily match this using sed, however I need to try using perl.
>
> This sed work just fine:
>
> sed -n '//,/<\/table>/p' thelo826.html
> |sed -n '//p'| sed -e 's/class=".*"//g'
>

If you're positive the html is consistently formatted,
(machine-generated for instance and you're the generator), you could
do something along this line:

my $regex = qr{ .*? 
.*? (  ).*? 
      }six;

{ local($/);
my $content = ; # substitute your  lexical filehandle
while ( $content =~ /$regex/g) {
   print "table=$1";
}
}

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: masks earlier declaration in same scope

2014-10-13 Thread Charles DeRykus
On Mon, Oct 13, 2014 at 1:04 AM, Boylan, Ross  wrote:
> perl -c adduser gives its first error as
> "my" variable $new_uid masks earlier declaration in same scope at adduser 
> line 283.
> First, it doesn't seem to me I'm declaring the variable at all at 283.  I 
> suppose it could be an implicit declaration if there wasn't a previous 
> declaration, but there is at 103.
> Second, I don't see any earlier declarations in any scope except the outer 
> one.
> Third, the variiable was declared, with "our $new_uid;" much earlier in the 
> file.
>
> Could anyone explain to me what's going on?  A couple other questions appear 
> after the code.
> 32  use warnings;
> 33  use strict;
> 34  use Debian::AdduserCommon;
> 35  use Getopt::Long;
> 36  use File::Spec::Functions;
> 37  use File::Touch;
> ...
>103  our $new_uid = undef;
> 
>160  # Parse options, sanity checks
>161  unless ( GetOptions ("quiet|q" => sub { $verbose = 0 },
> ...
>173  "uid=i" => \$new_uid,  # still in arguments to GetOptions
> Lines 103 and 173 are the only places $new_uid occurs in the text before line 
> 283.
>
>272  if ($use_template = &use_template) {
>273  # we are using templates
>274  if (check_template( $conf_dir, \%template)) {
>275  merge_template( \%template, \%system)
>276  }
>277  # rewrite request as needed
>278  if defined($new_name) {
>279  # trying to create a new user
>280  if (my @old = $$($template{uname}){$new_name}) {
>281  # requested user is in the template
>282  my $olduid = $$old[2];
> **283  dief( gtx("Specified UID %d for %s does not match template 
> UID of %d.\n"), $new_uid,
>284$new_name, $olduid) if defined($new_uid) && 
> $new_uid != $olduid;
>285  $new_uid = $olduid;
>286  my $oldgid = $$old[3];
>
> Bonus question #1: Where does the relevant scope start?  I think  it's 280, 
> but if none of the if's create scopes it could be the start of  the file.
>
> Bonus question #2: If I change 280 to  to   "if (my $old = " I get the 
> error
> "my" variable $old masks earlier declaration in same statement at adduser 
> line 282.
> Why?  I mean, there's only declaration in the statement, and it seems to be 
> on the first line even if the "statement" is everything up to the end of the 
> if .. else .. block.
>
> The archives indicate that syntax errors sometimes produce seemingly 
> unrelated "masks earlier declaration" errors, but even if this is a syntax 
> error (it seems more like a semantic problem to me) the error seems odd.


LIne 280 alone will generate  a syntax error:

$ perl -we 'if (my @old = $$($template{uname}){$new_
name}) {}'
 syntax error at -e line 1, near "$$("


Perhaps you meant somethng like:

   if (my @old = ( ${$template{uname}{$new_name}} ) ) {  }


But that's really bizarre too.  Did you really intend to declare and
populate an array and throw in a conditional all in a one-liner?

Do you know for instance that my @foo = $some_scalar is the equivalent
of just saying:  my @foo = ($some_scalar).

So, just a few thoughts... some more explanation of what that code is
intended to do would help.

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: return the list content

2014-09-12 Thread Charles DeRykus
On Wed, Sep 10, 2014 at 4:18 AM, Rob Dixon  wrote:
> On 09/09/2014 02:20, Ken Peng wrote:
>>
>>
>>> The second option creates the same array and populates it, but then
>>> copies it to another anonymous array, deletes the first array, and
>>> returns a reference to the copy.
>>
>>
>> Since this is a shadow copy, I don't think the first array will be
>> deleted completely. Isn't it?
>
>
> The second option is this
>
> sub myfunc {
>my @x=(1,2,3);
>return [@x];
> }
>
> And yes, the array @x is created, populated, and deleted completely
> every time the subroutine is called.
>

Hm,  I believe you're in error IIRC.  What happens is perl's internal array
structure for @x  is marked inaccessible when the sub exits.This enables
the struct to be more quickly resurrected on subsequent calls.  Scope is
preserved without doing extra work on re-entry.

Note the IIRC. Corrections welcome.

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Embed perl interpreter and call C function from perl?

2014-08-20 Thread Charles DeRykus
On Wed, Aug 20, 2014 at 8:42 AM, Manuel Reimer
 wrote:
> On 08/19/2014 06:58 PM, Jim Gibson wrote:
>>
>> Calling a C program from Perl can be done with the XS mechanism. XS stands
>> for eXternal Subroutine, and is the most common way to provide Perl-to-C
>> linkage. However, you may need to learn something about Perl internals.
>
>
> I know some basics about XS and I've written some small modules to get
> access to C functions that aren't available in plain Perl.
>
> I've also successfully written my own small example program that calls a
> perl script in an embedded interpreter.
>
> What I'm missing is the glue between both worlds.
>
> Is it possible to embed a perl interpreter in a C program, which itself
> defines a function "Foobar" which is declared in "foobar.h". Now I use the
> same "foobar.h" in a XS perl module to use this C interface. Is it possible
> to make my "module" interact with the function defined in the C program that
> embeds the interpreter?
>
> The idea is to somehow embed a perl interpreter into some software which
> only allows C to be used to write plugins. Those plugins are small ".so"
> files that have to use some header files which define the API. I somehow
> want to export the plugin API "into the Perl world" to make it possible to
> write plugins in Perl.
>

You might want to try the XS specific newsgroup:

lists.perl.org/list/perl-xs.html

Or, if that group "hat den Loeffel abgegeben",

   perlmonks.org


HTH,
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: one line script for word count

2014-06-30 Thread Charles DeRykus
On Mon, Jun 30, 2014 at 1:53 PM, Charles DeRykus  wrote:
> On Mon, Jun 30, 2014 at 1:41 PM, Charles DeRykus  wrote:
>> On Mon, Jun 30, 2014 at 11:57 AM, Sunita Pradhan
>>  wrote:
>>>  
>>
>> You could alter context, ie, change "if" to "while", to get the correct 
>> count:
>>
>>$c++ while $line =~ /\s\w+\s/g;
^^^

  $c++ while $line =~ /\s$w\s/g;

--
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: one line script for word count

2014-06-30 Thread Charles DeRykus
On Mon, Jun 30, 2014 at 1:41 PM, Charles DeRykus  wrote:
> On Mon, Jun 30, 2014 at 11:57 AM, Sunita Pradhan
>  wrote:
>> Hi
>>
>> I want to count number of occurrences of one word in a line within one
>> single line of perl script .
>>
>> My code :
>>
>> $c++ if ($line =~ /\s+$w\s+/g);
>> print "count $c\n";
>>
>>
>> It always return one even if $line contains same word twice . It does not do
>> the global match.
>> It works if I split the line but I want it in one line .
>>
>>
>
> In this case, perl always returns one if there's a match due to the
> boolean scalar context.
> With a match the return will be 1; otherwise 0. See the docs for a
> discussion of context,
>  eg, perldoc perldata.
>
> You could alter context, ie, change "if" to "while", to get the correct count:
>
>$c++ while $line =~ /\s\w+\s/g;
>
> --
> Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: one line script for word count

2014-06-30 Thread Charles DeRykus
On Mon, Jun 30, 2014 at 11:57 AM, Sunita Pradhan
 wrote:
> Hi
>
> I want to count number of occurrences of one word in a line within one
> single line of perl script .
>
> My code :
>
> $c++ if ($line =~ /\s+$w\s+/g);
> print "count $c\n";
>
>
> It always return one even if $line contains same word twice . It does not do
> the global match.
> It works if I split the line but I want it in one line .
>
>

In this case, perl always returns one if there's a match due to the
boolean scalar context.
With a match the return will be 1; otherwise 0. See the docs for a
discussion of context,
 eg, perldoc perldata.

You could alter context, ie, change "if" to "while", to get the correct count:

   $c++ while $line =~ /\s\w+\s/g;

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Need to Grep only fail count from the Pattern.

2014-06-24 Thread Charles DeRykus
On Tue, Jun 24, 2014 at 3:15 AM, Uday Vernekar  wrote:
> Hi all,
>
> I tried this its working fine when we have this pattern at hand,but the
> pattern is in a log file which is very large and i need to grep this pattern
> first from the generated log file then Match.how do i do it?
>

Once $pattern grepped out from log, then:

$fail_count = ( (split(/\Q$pattern/, $_) )[-2];

or maybe:

my $re = qr/\Q$pattern/;
$fail_count = ( split( /$re/, $_) )[-2];

   For explanation of "qr", see: Regexp Quote-Like Operators in perlop.

> On Tue, Jun 24, 2014 at 1:30 PM, Uday Vernekar 
> wrote:
>>
>> Thanks everybody will work out the Feasible option from all
>> these..Thanks a lot
>>
>>
>>
>> On Mon, Jun 23, 2014 at 10:12 PM, Charles DeRykus 
>> wrote:
>>>
>>> On Mon, Jun 23, 2014 at 2:42 AM, Uday Vernekar 
>>> wrote:
>>> > Hi All,
>>> >
>>> >
>>> > I have following Pattern from which I need to grep only the Fail count
>>> > and
>>> > store that in a variable.
>>> >
>>> > U/A/S|Test|Test   |Loop  | Run |Pass |Fail|
>>> > Arguments
>>> >  |  Name |Count|Count|Count|Count |
>>> >
>>> > -++---+-+-+-+-+--+---
>>> >  |  72| Traffic Test |  1|  11| 11|
>>> > 0|
>>> > (none)
>>> >
>>> > based on fail count value need to print
>>> >
>>> > if 0--Sucess
>>> > if >0--Fail
>>> >
>>>
>>> Another way:
>>>
>>>while ( ) {
>>> ...
>>> my $fail_count - ( split( /\|/, $_  ) )[-2];
>>>...
>>>}
>>>
>>> See: perldoc -f split
>>>
>>> --
>>> Charles DeRykus
>>>
>>> --
>>> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
>>> For additional commands, e-mail: beginners-h...@perl.org
>>> http://learn.perl.org/
>>>
>>>
>>
>>
>>
>> --
>> *
>> Don't ask them WHY they hurt you,
>> because all they'll tell you is lies and excuses.
>>  Just know they were wrong, and try to move on.
>> **
>
>
>
>
> --
> *
> Don't ask them WHY they hurt you,
> because all they'll tell you is lies and excuses.
>  Just know they were wrong, and try to move on.
> **

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Need to Grep only fail count from the Pattern.

2014-06-23 Thread Charles DeRykus
On Mon, Jun 23, 2014 at 2:42 AM, Uday Vernekar  wrote:
> Hi All,
>
>
> I have following Pattern from which I need to grep only the Fail count and
> store that in a variable.
>
> U/A/S|Test|Test   |Loop  | Run |Pass |Fail|
> Arguments
>  |  Name |Count|Count|Count|Count |
> -++---+-+-+-+-+--+---
>  |  72| Traffic Test |  1|  11| 11|   0|
> (none)
>
> based on fail count value need to print
>
> if 0--Sucess
> if >0--Fail
>

Another way:

   while ( ) {
...
my $fail_count - ( split( /\|/, $_  ) )[-2];
   ...
   }

See: perldoc -f split

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: File checks

2014-05-22 Thread Charles DeRykus
On Thu, May 22, 2014 at 1:40 PM, Manfred Lotz  wrote:
> Hi there,
> I want to check if a file is a plain file but not a symlink.
>
> It seems because -f returns true for a symlink that I have to do this:
> my $fname = 'somefile';
>
> if (  -f $fname  and not -l $fname ) {
> say "$fname is a plain file";
> }
> Is there a simpler way to do this?
>

Potentially shorter and arguably simpler if you use the special
underscore argument  to access file info for previous test, eg,

   if ( -f $fname  and  not -l _ ) {
   say...
   }

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Fail to match mixed quote pattern

2014-03-14 Thread Charles DeRykus
On Fri, Mar 14, 2014 at 4:26 AM, Alex Chiang
 wrote:

> I tried to extract string from perl script, so I wrote following script:
>
>   5# matching string
>   6 # sting start with ' or ".
>   7 # assume string is on same line.
>   8 #
>   9 my $pattern = '(\"|\').*\1';
>  10 my @array;
>  11 open (my $file, "<", "str");
>  12 while (my $line = <$file>) {.
>  13 if($line =~ /$pattern/) {
>  14 push (@array, $&);
>  15 }
>  16 }
>  17
>  18 for (@array) { print "$_\n"; }
>
>
> the str sample file :
> ---
> 'okay i know now'
> "from time to time" 'let us go'
> this is awkward
> 
>
> I would expect the output match three of them, however, it only matches:
> --
> 'okay i know now'
> "from time to time"
> ---
> leaving 'let us go' unmatched.
>
> I don't know how to describe this problem, Can anyone help me with this ?
>

Here's a safer, more efficient version:
see: perldoc perlre

* uses 'qr' for reg.exp. compilation
* avoid speed penalty of $& with /p switch
* \g{} captures instead of \1 which can  be  ambiguous in case of \10 eg.

my $pattern = qr/("|').*?\g{1}/;
my @array;
while (my $line = <$file>){
   while($line =~ /$pattern/pg) {
  push (@array, ${^MATCH});
   }
}

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: regex and parse

2014-03-11 Thread Charles DeRykus
On Tue, Mar 11, 2014 at 10:01 AM, Ariel Hosid  wrote:
> Hello everyone!
> Can anyone recommend me literature that treats regular expressions and how
> to analyze files?

Some perl resources:

perldoc perlrequick(Perl regular expressions quick start)
perlretut   (Perl reg exp tutorial)
perlre   (Perl regular expressions, the rest of the story)

.--
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Fwd: perl regexp performance - architecture?

2014-02-17 Thread Charles DeRykus
On Mon, Feb 17, 2014 at 4:25 PM, Phil Smith  wrote:

> On Mon, Feb 17, 2014 at 6:16 PM, Charles DeRykus wrote:
>
>>
>> On Mon, Feb 17, 2014 at 12:41 PM, Phil Smith  wrote:
>>
>>> I'm currently loading some new servers with CentOS6 on which perl5.10 is
>>> the standard version of perl provided. However, I've also loaded perl5.18
>>> and I don't think the version of perl is significant in the results I'm
>>> seeing. Basically, I'm seeing perl performance significantly slower on my
>>> new systems than on my 6 year old systems.
>>>
>>> Here's some of the relevant details:
>>>
>>> + 6 year old server, 32 bit architecture, CentOS5 perl5.8
>>> perl, and in particular regexp operations, perform reasonably fast.
>>>
>>> + Very new server, 64 bit architecture, CentOS6, perl5.10 (and have
>>> tried perl5.18)
>>> perl, and in particular regexp operations, perform significantly slower
>>> than on the 6 year old server. That struck me as odd right off. I though
>>> surely, perl running on a modern high-end cpu is going to beat out my code
>>> running on 6 year old hardware.
>>>
>>> I've compared CPU models at various CPU benchmarking sites and the new
>>> CPUs, as you would expect, are ranked significantly higher in performance
>>> than the old.
>>>
>>> I've also installed perl5.8 on the new 64bit servers and the performance
>>> is similar to that of perl5.10 and perl5.18 on the same 64bit servers.
>>> Given that, I don't think perl version plays a significant factor is the
>>> performance diffs.
>>>
>>> Is it an accepted fact that perl performance takes a hit on 64 bit
>>> architecture?
>>>
>>> I've tried comparing some of the perl -V and Config.pm results looking
>>> for significant differences. That output is pretty verbose and the most
>>> significant difference is the architecture.
>>>
>>> I could provide some of my benchmarking code if that would be of help.
>>> The differences are significant. The only reason I'm looking at this is
>>> because I could see right off that some of my code is taking 30-40% longer
>>> to run in the new environment. Once I started putting in some timing
>>> with Time::HiRes I could see the delay involved large amounts of regexp
>>> processing.
>>>
>>> Right now, I'm just looking for any opinions on what I'm seeing so that
>>> I know the architecture is the significant factor in the performance
>>> degradation and then consider any recommendations for improvements. I'm
>>> happy to provide further relevant details.
>>>
>>
>> This sounds like it  could be something OS-specific and, googling
>> "CentOS regex performance" generates hits, eg,
>>
>>
>>>
>>> http://pkgs.org/centos-5/puias-computational-x86_64/boost141-regex-1.4.0-2.el5.x86_64.rpm.html
>>>
>>
>> No, I really don't think it is specific to a version of CentOS. I've
>> installed various permutations of 32 and 64 bit CentOS 5 and 6. The better
>> performance seems to follow the 32 bit architecture rather than a specific
>> Perl version or CentOS version.
>>
>
Newer perl regex engines have added Unicode support which can
add drag. I'd be surprised though if just the 64-bit architecture itself
was totally responsible for major slowdowns.  Some of the issues are
mentioned here:

http://stackoverflow.com/questions/17800112/upgraded-from-perl-5-8-32bit-to-5-16-64bit-regex-performance-hit

Per above, some of the items, you'll need to be careful with:

were both Perls compiled with the same flags?
are both perls threaded perls (disabling threading support makes it
faster)
how big are your integers? 64 bit or 32 bit?
what compiler optimizations were chosen?
did your previous Perl have some distribution-specific patches
applied?
Basically, you have to compare the whole perl -V output

-- 
Charles DeRykus



As you can see,  you need to be carefully examining the comparison
scenarios.

-- 
Charles DeRykus


Re: perl regexp performance - architecture?

2014-02-17 Thread Charles DeRykus
On Mon, Feb 17, 2014 at 12:41 PM, Phil Smith  wrote:

> I'm currently loading some new servers with CentOS6 on which perl5.10 is
> the standard version of perl provided. However, I've also loaded perl5.18
> and I don't think the version of perl is significant in the results I'm
> seeing. Basically, I'm seeing perl performance significantly slower on my
> new systems than on my 6 year old systems.
>
> Here's some of the relevant details:
>
> + 6 year old server, 32 bit architecture, CentOS5 perl5.8
> perl, and in particular regexp operations, perform reasonably fast.
>
> + Very new server, 64 bit architecture, CentOS6, perl5.10 (and have tried
> perl5.18)
> perl, and in particular regexp operations, perform significantly slower
> than on the 6 year old server. That struck me as odd right off. I though
> surely, perl running on a modern high-end cpu is going to beat out my code
> running on 6 year old hardware.
>
> I've compared CPU models at various CPU benchmarking sites and the new
> CPUs, as you would expect, are ranked significantly higher in performance
> than the old.
>
> I've also installed perl5.8 on the new 64bit servers and the performance
> is similar to that of perl5.10 and perl5.18 on the same 64bit servers.
> Given that, I don't think perl version plays a significant factor is the
> performance diffs.
>
> Is it an accepted fact that perl performance takes a hit on 64 bit
> architecture?
>
> I've tried comparing some of the perl -V and Config.pm results looking for
> significant differences. That output is pretty verbose and the most
> significant difference is the architecture.
>
> I could provide some of my benchmarking code if that would be of help. The
> differences are significant. The only reason I'm looking at this is because
> I could see right off that some of my code is taking 30-40% longer to run
> in the new environment. Once I started putting in some timing
> with Time::HiRes I could see the delay involved large amounts of regexp
> processing.
>
> Right now, I'm just looking for any opinions on what I'm seeing so that I
> know the architecture is the significant factor in the performance
> degradation and then consider any recommendations for improvements. I'm
> happy to provide further relevant details.
>

This sounds like it  could be something OS-specific and, googling
"CentOS regex performance" generates hits, eg,


>
> http://pkgs.org/centos-5/puias-computational-x86_64/boost141-regex-1.4.0-2.el5.x86_64.rpm.html
>

HTH,
Charles DeRykus


Re: OO perl programming

2014-02-05 Thread Charles DeRykus
On Wed, Feb 5, 2014 at 2:30 PM, kavita kulkarni
wrote:

> Can somebody suggest me good book to learn/practice object oriented Perl
> programming.
>
> With a recently modern perl,  I'd start with perl's own tutorial to get
a short overview.

   See:  perldoc perlootut

And, then go on to other suggested sources... or not :)

TIMTOWDI

-- 
Charles DeRykus


Re: mv Is Not Working the Same Way Under System as Under a Shell.

2014-01-30 Thread Charles DeRykus
On Wed, Jan 29, 2014 at 2:10 PM, Martin G. McCormick <
mar...@server1.shellworld.net> wrote:

> I have a perl script that I run as root which needs to
> move a file from where it is to another directory.
>
> I keep getting the "Usage"  help message and a
> permission denied. If I su to root and manually make the move,
> it works.
>
> The perl script is not trying to run suid to root. I am
> root when I call it. The line in question reads:
>
> system(
> "mv $directories$filename \"$directories\"deleted_keys/"
> );
>
> $directories and $filename are correctly set at the time. The
> output from the script is:
>
> usage: mv [-f | -i | -n] [-v] source target
>mv [-f | -i | -n] [-v] source ... directory
> /var/named/etc/namedb/dynamic/okstate.edu/deleted_keys/: Permission denied
>
> As I said, it works if I become root and manually move the file
> in question.o
> This is basically a script for moving expired dnssec keys out of
> the directory and in to a morgue of dead keys which we will keep
> around if there is trouble-shooting to be done later.
>
> The script, when run, is owned by root and run by root
>



Another recommendation:

File::Copy is core now I believe, is portable, faster, easier and more
transparent  than deciphering shell error returns, and enables you
to avoid the nasty quoting issues of a 'system' call:

use File::Copy;
move( $file1, $file2) or die "move: $!";

See: perldoc File::Copy

-- 
Charles DeRykus


Re: perlre(1) and substitution evaluations

2013-11-30 Thread Charles DeRykus

On 11/30/2013 5:16 AM, Lars Noodén wrote:

On 11/30/2013 02:55 PM, Charles DeRykus wrote:

[ ..

Thanks.  I see those in perlop and perlfunc.  In perlfunc, it is grouped
as "Regular expressions and pattern matching" though that man page just
points to perlop.

A really clear description in perlre would help, since the other
modifiers are already there and they belong all together.  The two s///
modifiers, /e and /r, should be at least named in that group at least as
one-line summaries.
Yes.  IMO it should be much easier to find the doc ref's for /e and even 
/r too.
I seem to recall strong advocacy in the past for adding this or similar 
pointers.

Long overdue :)

--
Charles DeRykus

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: perlre(1) and substitution evaluations

2013-11-30 Thread Charles DeRykus

On 11/30/2013 4:07 AM, Lars Noodén wrote:

perlre(1) seems to be missing information about substitution evaluations
with the /e option.  The functionality is present in perl:

perl -e '$_=2; s/2/1+3/e; print'

But it is not listed in the pod documentation for v5.16.3 or v5.18.1.
The modifier /e is described in "Programming Perl", 4th ed, pp 186,
254-255.

Where should suggestions for corrections be sent?
Could something like the text below be added?

Regards,
/Lars

$ diff perlre.pod perlre.pod.orig
108,113d107
< =item e
< X
<
< Treat the replacement portion as an interpreted expression.
< Each additional C modifier after the first functions as an eval()
around the code to execute.
<


See the substitution operator in perlop:

|||<http://perldoc.perl.org/functions/s.html>| A |/e| will cause the 
replacement portion to be treated as a full-fledged Perl expression and 
evaluated right  then and there. It is, however, syntax checked at 
compile-time. A second |e| modifier will cause the   replacement portion 
to be |eval <http://perldoc.perl.org/functions/eval.html>|ed before 
being run as a Perl expression.

...

Here's the cross ref. in perlre:

For reference on how regular expressions are used in matchings of 
"m//",
operations, plus various examples of the same, see discussions of 
"m//",
"s///", "qr//" and "??" in "Regexp Quote-Like Operators" in 
perlop.ls of

 Modifiers quoted constructs" in perlop

--
Charles DeRykus


--
Charles DeRykus


Re: Need help with a programming problem

2013-10-02 Thread Charles DeRykus
On Wed, Oct 2, 2013 at 5:10 PM, Peter Holsberg
wrote:

> Charles DeRykus has written on 10/2/2013 5:49 PM:
> >
> > Wouldn't a manual edit be easier... or is this a recurrent problem?
> > If recurrent, a messy solution may be possible but fragile unless
> > the html formatting is invariant - what if, for instance ''
> > appears with whitespace embedded between/inside tags..?
>
> Recurrent.
> Invariant.
>
>
Ok, assuming  edit replacements can be done independently, here's a template
that might help:


use File::Slurp; use strict; use warnings;

my $input= read_file("...")or die "can't read ... ";
my $append = read_file("...")   or die "can't read ...";

my $token =  qr/^)$/m;'
$input =~ s/$token/$1$append/or die "can't find $token";

my $replace = << 'END';
...
END
$token =  qr{^$}m;
$input =~ s/$token/$replace/m  or die "can't find $token";
__END__


-- 
Charles DeRykus


Re: How Much is Too Much? (WAS: formatting a list)

2013-10-02 Thread Charles DeRykus
On Wed, Oct 2, 2013 at 1:58 AM, James Griffin  wrote:

> * Shawn H Corey  [2013-10-01 17:34:06 -0400]:
>
> > On Tue, 1 Oct 2013 14:14:16 -0700
> > Charles DeRykus  wrote:
> >
> > > I'm not bucking for "net nanny" but, while full solutions and
> > > follow-on discussions can be enlightening, I wonder if they're really
> > > advantageous to the OP.  Not to embarrass anyone but there was no
> > > mention of DIY attempts, no soliciting of hints  or approaches, or
> > > even mention of  being stuck or frustrated thinking about how to
> > > start.
> > >
> > > A  "guru service while you wait " may  be excellent but disciples
> > > will fail to ever get  their G.E.D. (guru equivalency diploma).
> >
> > On the other hand, any program under 200 lines is trivial and is a
> > warm-up exercise. ;)
> >
> > How are newbies going to learn good coding practices without reading
> > good code?
>
> Indeed. People learn in different ways. Some people, myself included,
> learn through seeing examples which then can be used to read up further
> with a better insight and understanding of what they're looking at/reading.
> Others, can simply pick out information from books and learn without much
> guidance. Sometimes, the text written by people may not be as intuitive to
> others reading it as the author may believe. Of course, that doesn't mean
> those learning shouldn't make an effort to understand first and rely solely
> on the examples and guidance of others


Agreed - and that's why I think the examples can be enlightening for every
level.  However,  this example while demanding a fair level of skill wasn't
brain surgery and even newbies and students should be able to make an
initial attempt at a solution and report what they saw or where they got
stuck.   Or even preface their post with  "I tried 'split' but even
thinking about the next step gives me a headache. What would you
suggest?".   Now the  expectation is tilting  to  "Solve it for me... you
got nothing better to do and I'm busy... too busy to waste my time
detailing what if anything I did to help myself".

-- 
Charles DeRykus


Re: formatting a list

2013-10-01 Thread Charles DeRykus
On Mon, Sep 30, 2013 at 7:43 AM, Rajeev Prasad  wrote:

> thank you Shawn. this works nicely for me.
>
>
>   --
>  *From:* Shawn H Corey 
> *To:* beginners@perl.org
> *Cc:* Rajeev Prasad 
> *Sent:* Saturday, September 28, 2013 8:49 AM
> *Subject:* Re: formatting a list
>
> On Fri, 27 Sep 2013 22:59:01 -0700 (PDT)
> Rajeev Prasad  wrote:
> ...
>

I'm not bucking for "net nanny" but, while full solutions and follow-on
discussions can be enlightening, I wonder if they're really advantageous to
the OP.  Not to embarrass anyone but there was no mention of DIY attempts,
no soliciting of hints  or approaches, or even mention of  being stuck or
frustrated thinking about how to start.

A  "guru service while you wait " may  be excellent but disciples will fail
to ever get  their G.E.D. (guru equivalency diploma).

-- 
Charles DeRykus


Re: Sleep

2013-09-16 Thread Charles DeRykus
> On Sun, Sep 15, 2013 at 6:59 PM, Charles DeRykus 
> wrote: left: ", $start+$sleep -time() };
> ...

Actually,  this is wrong because if sleep(3) is interrupted by any signal
it
will return, so something like this should work, eg

my $secs_to_sleep = 60;
my $start = time();
my $end = $start + $secs_to_sleep;

my $slept;
do  {
  local  $SIG{USR1} = sub{ say "time left: ", $end - time()};
  my $slept = sleep($secs_to_sleep);
  $secs_to_sleep -= $slept;
} while ( $secs_to_sleep >  0 );

-- 
Charles DeRykus


Re: parsing html

2013-08-08 Thread Charles DeRykus
On Thu, Aug 8, 2013 at 10:18 AM, David Precious wrote:

> On Thu, 8 Aug 2013 22:42:01 +0530
> Unknown User  wrote:
>
> > What would be the best module available for parsing html in your
> > opinion? My intention is to parse html that contains a table of 5
> > columns and any number of rows
>
> For parsing HTML tables, you want HTML::TableExtract, IMO.
>
> https://metacpan.org/module/HTML::TableExtract
>
> It makes life easy.
>
>
>
>
> I'm with David since the stated objective was to extract table info. As
powerful as the other parsing modules are, you certainly would be grinding
out more code.

-- 
Charles DeRykus


Re: Convert any date format to ISO

2013-07-27 Thread Charles DeRykus
On Fri, Jul 26, 2013 at 4:45 AM, Perl Beginners  wrote:

> On 07/25/2013 04:40 PM, Charles DeRykus wrote:
>
>>
>>
>>
>> On Wed, Jul 24, 2013 at 10:56 PM, Michael Brader <
>> mbra...@internode.com.au 
>> <mailto:mbra...@internode.com.**au>>
>> wrote:
>>
>>
>> On 07/25/2013 10:14 AM, mimic...@gmail.com
>> <mailto:mimic...@gmail.com> wrote:
>>
>>> I was trying to use Date::Simple to convert date from DD-MM-
>>> to ISO standard -MM-DD,  but it produced error below because
>>> it returned undef when the date passed is not ISO standard.
>>>
>>
>> Yeah on quick scan of the perldoc it looks like Date::Simple
>> doesn't offer much in the way of parsing.
>>
>>  [...]
>>>
>>> Most of the date modules on CPAN cannot do the job for me. I
>>>
>>
>> Date::Manip and friends are wonderfully versatile but with even in this
>> simple case, it does start to get a bit twisty with special parse and
>> output methods:
>>
>> IMO, it'd be superb if the earlier functional interface or even
>> parse_date  in Date::Manip::Date would just accept a hash ref of
>> non-standard  format specs.  Then, you could just output with UnixDate as
>> usual.
>>
>>
>>  eg,  ParseDate( ... ,   { fmt1="%d-%m-%Y", fmt2=... } )
>>
>

>  Perhaps I'm missing something... but why do you want a hash ref?  Why not
> just a list (or listref) of formats. I'm not sure what the keys 'fmt1',
> 'fmt2', play in your suggestion (and if they don't play any role, a listref
> would definitely be better).
>
> So, if I understand your suggestion, what you want is this:
>
>$date->parse( $string, $listref, @opts );
>
> where $listref is optional, but if included, it would be a list of
> formats(similar to parse_format) thatthe date would be parsed against.  If
> they all failed, it could then fall back on the standard formats. If
> $listref were omitted, only the standard formats would be used.
>
> Does this sound like what you're suggesting?
>
>
Yes  the listref would be another simpler way.  I can't see
any value for the hashref unless someone had a need for a
shortcut identifier for the actual format.

-- 
Charles DeRykus


Re: Convert any date format to ISO

2013-07-25 Thread Charles DeRykus
On Wed, Jul 24, 2013 at 10:56 PM, Michael Brader
wrote:

>
> On 07/25/2013 10:14 AM, mimic...@gmail.com wrote:
>
>  I was trying to use Date::Simple to convert date from DD-MM- to ISO
> standard -MM-DD,  but it produced error below because it returned undef
> when the date passed is not ISO standard.
>
>
> Yeah on quick scan of the perldoc it looks like Date::Simple doesn't offer
> much in the way of parsing.
>
>  [...]
>
> Most of the date modules on CPAN cannot do the job for me. I spent time
> reading documentations but as it now stands, I have to do  this myself.
>
>
> There are at least 2 modules that can definitely do the job for you,
> Date::Manip::Date and DateTime (with DateTime::Format::Natural). I usually
> use the latter, but since you want the former:
>
> Have a look at the documentation for Date::Manip::Date and look for
> parse_format and printf
>
>
>
Date::Manip and friends are wonderfully versatile but with even in this
simple case, it does start to get a bit twisty with special parse and
output methods:


use Date::Manip::Date;
my $date = Date::Manip::Date->new;

my $err=$date->parse_format("%d-%m-%Y","29-01-1972")
  or  die "can't parse date: $err";

print $date->printf("%m-%d-%Y");   # 01-29-1972

P.S.

IMO, it'd be superb if the earlier functional interface or even parse_date
in Date::Manip::Date would just accept a hash ref of non-standard  format
specs.  Then, you could just output with UnixDate as usual.


 eg,  ParseDate( ... ,   { fmt1="%d-%m-%Y", fmt2=... } );


-- 
Charles DeRykus


Re: url_encode for LWP POST

2013-07-25 Thread Charles DeRykus

On 7/25/2013 12:57 AM, Feng He wrote:
Would LWP::UserAgent call the url_encode() method from URL::Encode 
automatically for the posted content?



  use LWP::UserAgent;
  $ua = LWP::UserAgent->new;

  my $req = HTTP::Request->new(
  POST => 'http://rt.cpan.org/Public/Dist/Display.html');
  $req->content_type('application/x-www-form-urlencoded');
  $req->content('Status=Active&Name=libwww-perl');

  my $res = $ua->request($req);
  print $res->as_string;

If I recall correctly, no it won't.  And,  you can confirm that by 
examining:


$req->as_string;


Probably the easiest way to do this is with HTTP::Request::Common which
will handle escaping the form parameters for you, eg,


   use HTTP::Request::Common;
   use LWP::UserAgent;

   $ua->request( POST 'http://rt.cpan.org/Public/Dist/Display.html'
 [ Status => ..., Name=>... ] );


--
Charles DeRykus


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: last

2013-06-28 Thread Charles DeRykus
On Fri, Jun 28, 2013 at 1:21 AM, Dr.Ruud  wrote:

> On 28/06/2013 09:08, Charles DeRykus wrote:
>
>  [...]  I was making a case that "do"  in limited cases could be a
>>
>> shorter and/or slightly clearer idiom.
>>
>
> I think the context was if you would ever go as far as using double braces
> to make a loop-construct out of 'do'. But even more how combining a do {}
> with a statement modifier can easily lead to confusion, see the examples in
> perlsyn.
>
> In a serious environment, code should be readable much more than writable.
> So spend the extra minutes to make it as clear and non-ambiguous as you
> can. Then someone else can more easily fix any bugs you introduced, without
> having to ask you a lot of questions, and without having to rewrite the
> whole thing.
>
>
Exactly.  That's why I mentioned 'do'  should probably draw a more explicit
caution in the docs. And I'd agree  double braces to make 'do'  more
loop-like (loop-ish?) is the wrong approach and reduces readability. But,
in a simple scenario,  a  do'  with its  clear mirroring of "do this until
that happens"  can enhance readability.

-- 
Charles DeRykus


Re: last

2013-06-28 Thread Charles DeRykus
On Thu, Jun 27, 2013 at 10:20 PM, shawn wilson  wrote:

> >...
> > True.  But, "do" should probably draw a more explicit caution in the docs
> > since there are less tricky ways in most cases.
> >
> > However, there may be a few places when 'do' isn't always a don't :)
> >
> > 'do' might be a shorter, more readable idiom in the sense of "do
> something
> > until a condition occurs":
> >
> I can't agree with the either or here ... [snip]
>
> > perl -e 'do {$in =<>; ... } until $in =~ /q/'
> >
> >  vs.
> >
> > perl -e 'while ( $in = <>; ... ) { ... last if $in =~ /q/}'
> >
> I find a combination of the two is most useful for quickly generating
> reports:  [...snip]
> ...
>

Hm, this wasn't an argument for exclusive "either/or" usage at all. Rather
I was making a case that "do"  in limited cases could be a shorter and/or
slightly clearer idiom.

-- 
Charles DeRykus


Re: last

2013-06-27 Thread Charles DeRykus
On Thu, Jun 27, 2013 at 1:31 PM, Dr.Ruud  wrote:

> On 27/06/2013 22:01, Shawn H Corey wrote:
>
>> On Thu, 27 Jun 2013 21:53:46 +0200
>> "Dr.Ruud"  wrote:
>>
>  See also 'Statement Modifiers' in perlsyn.
>>> There it is shown how to make next and last work with do{}. I read
>>> that as a rather funny way to discourage people from do-ing it.
>>>
>> "Here be dragons." I would say that was a warning to avoid it
>> altogether.
>>
>
> The "Here be dragons." there, is about something different, namely the "my
> $x if ... ;" type of code.
> (at least in the version I last read, 5.14.2
>
>
True.  But, "do" should probably draw a more explicit caution in the docs
since there are less tricky ways in most cases.

However, there may be a few places when 'do' isn't always a don't :)

'do' might be a shorter, more readable idiom in the sense of "do something
until a condition occurs":

perl -e 'do {$in =<>; ... } until $in =~ /q/'

 vs.

perl -e 'while ( $in = <>; ... ) { ... last if $in =~ /q/}'



-- 
Charles DeRykus


Re: Handling special characters in peoples names in XML

2013-06-25 Thread Charles DeRykus
On Wed, Jun 26, 2013 at 7:45 AM, Peter Gordon wrote:

> On Wed, 26 Jun 2013 12:36:01 +1200, Gregory Machin wrote:
> >
> >Looks like the data already is utf8, but the header of the XML
> >specifies otherwise.
> >How do you parse the data? Can you give us a short example file?
> >
> >Jenda
>


> This is a bit of code I adapt to whichever encoding I require.
>
> use open ":encoding(UTF-16le)";
> while( <> ) {
> s/\x{FF}\x{FE}|\x{}//;  # Remove BOM.
> s/[\x0A\x0D]+$//;   # Remove CR LF
>
> If you can get the data into a text editor which has a "convert" option,
> you can use it to either find out the encoding &/or change it to utf8.
> If you have a file with mixed encodings, you have my sympathies.
>


Encode::Guess may occasionally be useful:

>
 use Encode::Guess;

 my $decoder=Encode::Guess->guess("Grégoire");
 die $decoder unless $decoder;
 print $decoder->name;#---> utf8

-- 
Charles DeRykus


Re: Perl error codes and warnings

2013-05-28 Thread Charles DeRykus

On 5/28/2013 8:19 PM, *Shaji Kalidasan* wrote:

Greetings,

Where can I get more information on Perl's most common error codes? Is 
there a single source (repository/resource) for such most frequently 
encountered error codes?


[code-1]
use strict;
use warnings;

[ ...  ]

The warnings are fairly intuitive but you can add:

use diagnostics qw/-verbose/;

for added explanations.

--
Charles DeRykus




Re: Can't close filehandle

2013-05-01 Thread Charles DeRykus
On Wed, May 1, 2013 at 12:57 PM, Manfred Lotz  wrote:

> On Wed, 1 May 2013 12:00:18 -0700
> Charles DeRykus  wrote:
>
> > > ...
> > > Thanks for your detailed explanations. I think that close should
> > > work as I cannot see any reason why a failure of a command closes
> > > the pipe prematurely.
> >
> > Actually,  everything is ok until the close which checks both the
> > status from reaping the child and the close itself:
> >
>
> >> OK, the issue is that close is more than just close. Looking from this
> >> side it works like designed.
>
> 'perldoc -f close'hints at this although it could be clearer that
>
$? could potentially cause close to
fail:

...
If the filehandle came from a piped open, "close" returns false
if one of the other syscalls involved fails or if its program
exits with non-zero status. If the only problem was that the
program exited non-zero, $! will be set to 0. Closing a pipe
also waits for the process executing on the pipe to exit--in
case you wish to look at the output of the pipe afterwards--and
        implicitly puts the exit status value of that command into $?
and "${^CHILD_ERROR_NATIVE}".

-- 
Charles DeRykus


Re: Can't close filehandle

2013-05-01 Thread Charles DeRykus
> ...
> Thanks for your detailed explanations. I think that close should work
> as I cannot see any reason why a failure of a command closes the pipe
> prematurely.

Actually,  everything is ok until the close which checks both the
status from reaping the child and the close itself:

The open can actually  be written like this for more into:

my $pid = open(my $fh, '-|', ... or die ...;   # pid is forked process id
warn "made it past open ok...\n";
close( $fh) or die "child $pid status=$?  close error=$!";

So the close can be written  to see whether the child  process had a
problem, ie, $?  or whether it was  the 'close' itself that failed, ie, $!.

Output without 'autodie':
 made it past open ok...
 child 4872 status=256  close error=Inappropriate I/O control operation
at...

With autodie though, the message is much more obscure:
 made it past ok...
 Can't close(GLOB(0x64dcf8)) filehandle: '' at...

-- 
Charles DeRykus


Re: Can we use string as variable name

2013-04-30 Thread Charles DeRykus
> On Tue, Apr 30, 2013 at 10:07 AM, Piyush Verma <114piy...@gmail.com>
> wrote:
> Hi,I want to use string as a variable name, please explain if there is
any way
> in perl.
> ...

This is a FAQ.  See:


http://perldoc.perl.org/perlfaq7.html#How-can-I-use-a-variable-as-a-variable-name
?

-- 
Charles DeRykus


Re: Any alternative for substr() function

2013-04-12 Thread Charles DeRykus
On Fri, Apr 12, 2013 at 4:23 AM, kavita kulkarni
wrote:

> Thanks all, got many ideas from you..
>
> My script took ~7 min to run with data file of ~50,000 lines with
> substr()/unpack() enabled and same script took ~2 min after disabling
> substr()/unpack().
> ...
>
> For "Devel::NYTProf", I need to check if my SA if he will allow me to
> install


You can usually just install the module under your own directory...

See:  perldoc -q "How do I keep my own module/library directory?"

-- 
Charles DeRykus


Re: no warnings inside a loop

2013-04-03 Thread Charles DeRykus
On Wed, Apr 3, 2013 at 4:29 PM, Angela Barone
wrote:

> I'm just curious about this.  If you put "no warnings" inside a
> loop, is it good only for that loop, or will it be in effect until the end
> of the script?
>


See: perldoc perllexwarn

>From above doc:

...
use warnings;
my @a;
{
no warnings;
my $b = @a[0];
}
my $c = @a[0];

   The code in the enclosing block has warnings enabled, but the inner
block has them disabled.
   ...

-- 
Charles DeRykus


Re: IPC::Open3 Usage

2013-03-21 Thread Charles DeRykus
On Thu, Mar 21, 2013 at 6:41 PM, Charles DeRykus  wrote:
> On Thu, Mar 21, 2013 at 3:12 PM, Dominik Danter  wrote:
>> Hi I just don't understand the perlfaq example. All I want is to capture 
>> output
>> of an external command's stdout and stderr. Here is what I've tried:
>>
>>
>> sub get_exit() {
>> my ($exit_status, $std_out, $std_err) = @_;
>> my %error_codes = (
>> 1024 => 'uid already exists',
>> 256  => 'not root',
>> 0=> 'success',
>> );
>> my $message = $error_codes{$exit_status};
>> return {
>> message => (defined $message ? $message : 'unknown exit status'),
>> exit_status => $exit_status,
>> std_out => (defined $std_out ? $std_out : 'no standard output
>> produced'),
>> std_err => (defined $std_err ? $std_err : 'no error output
>> produced'),
>> };
>> }
>>
>> sub change_id {
>> my %command = (
>> uid => 'usermod --uid',
>> gid => 'usermod --gid',
>> );
>> my ($type, $username, $new_id) = @_;
>> my ($std_in, $std_out, $std_err, $exit_status);
>> eval {
>> my $pid = open3($std_in, $std_out, $std_err,
>> "$command{$type} $new_id $username");
>> waitpid( $pid, 1);
>> $exit_status = $? >> 8;
>> };
>> return &get_exit($exit_status, $std_out, $std_err );
>> }
>>
>>
>> print Dumper(user::change_id('uid','bla',997));
>>
>>
>> Here is my output:
>> Use of uninitialized value $exit_status in hash element at user.pm line 31.
>> $VAR1 = {
>>   'std_err' => 'no error output produced',
>>   'std_out' => \*Symbol::GEN1,
>>   'exit_status' => undef,
>>   'message' => 'unknown exit status'
>> };
>>
>>
>> The command should fail since it lacks required permission, but I'd like to
>> handle the error messages gracefully.
>
> waitpid( $pid, 1);
> ^^^
>
> This looks amiss.  Normally, it's waitpid($pid,0) for a blocking
> wait or maybe POSIX's WNOHANG. for an async wait. See
> perldoc -f waitpid.
>
> --
> Charles DeRykus.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Mechanize: first attempt at scraping (should be something trivial)

2013-03-13 Thread Charles DeRykus
On Wed, Mar 13, 2013 at 1:08 PM, G M  wrote:
> Hi,
>
> Yeah I tried putting a die line in after doing a bit of googling, I've got a
> print "mech ran" line where you've got "die", doesn't print anything out
> though :(
>
>
>

Hm, the problem is that Mech by default throws fatal errors so if
it couldn't fetch content, your program dies before "mech ran"
occurs. Only if you said $agent->new(autocheck=>0), would you
see it.

You can see the differing output in these:

$agent->new(autocheck=>0);  # toggle 0/1
$agent->get("http://nowhere.com/nono";);
print "mech ran";

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Mechanize: first attempt at scraping (should be something trivial)

2013-03-13 Thread Charles DeRykus
On Wed, Mar 13, 2013 at 12:09 PM, G M  wrote:
>
> Hi all,
>
> I'm making an attempt at my first screen scraping script.
>
> For some reason the script doesn't continue after the invocation of the get 
> method on the last line:
>
> use strict;
> use WWW::Mechanize;
> use HTML::TokeParser;
> use Data::Dumper;
> print "Content-type: text/html\n\n";
> print "setting up mech";
> my $agent = WWW::Mechanize->new();
>$agent->agent_alias('Windows Mozilla');
>print "mech setup";
>   $agent->get('http://www.easyjet.com/en/');
>
>
> Can anyone see anything wrong with this?  I've tried double quotes and 
> different urls but it doesn't attempt to "get" the page.
>

Hm,  what code follows the "get"?

Always a good idea to  check for errors in case of site
outage for instance.  However this worked for me a few
moments ago when  I tried:

  $agent->get(...);
  die $agent->status unless $agent->success;  ";
  print "content:  $a->content";

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Return values more than 256?

2013-03-08 Thread Charles DeRykus
On Fri, Mar 8, 2013 at 2:49 AM, Dr.Ruud  wrote:
> On 2013-03-07 10:21, WFB wrote:
>
>> waitpid($pid, 0);
>> close($trexe);
>> my $tr_ret = ($?>>8);
>
>
> Never postpone the reading of a global variable,
> just snapshot it as early as possible.
>
>   my $child = waitpid $pid, 0;
>   my $child_error = $?;  # snapshot a global
>
>   $child == -1 and die "No child with pid $pid found";
>
>   close $trexe or die "ERROR: $!";
>
>   my $tr_ret = ($child _error >> 8);
>

Or,  just eliminate the waitpid altogether since
there's an implicit waitpid when the pipe gets
closed. It gets a bit confusing but the pipe
close needs to be checked first and then
subsequently the child return as another poster
demonstrated:


   close $trexe or warn $! ? "Error closing $tr pipe: $!"
: "Exit status $? from $tr";

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Non interactive interaction

2013-02-28 Thread Charles DeRykus
On Thu, Feb 28, 2013 at 2:48 AM, Andrew  wrote:
> I'm a brand newbie to cpan and relatively inexperienced with perl.  I was
> given some cpan commands to follow for a third
> party application I'm trying to install/build, but I want to script (bash)
> these commands as chances are I'll be
> reinstalling a bunch of times after I screw it up.
>
> The module installs are easy (cpan modulename).  However, I need to do "o
> conf commit" and
> possibly other somewhat similar commands.  I can't find anything that
> explicitly explains how.
>
> My investigations reveal that it may be the case that I can use YAML,
> autocommit, expect and/or mkmyconfig to accomplish
> this task, but I'm in way over my head.  I didn't want this to be a major
> project, I just wanted to automate
> the installation of a few modules and whatnot so I can move on with my life.
> This is for a personal Linux (Ubuntu)machine
> so yes I'm root & I want to do this on a system wide basis.
>

I haven't used it but App::cpanminus may be a
help:

http://search.cpan.org/~miyagawa/App-cpanminus-1.6002/lib/App/cpanminus.pm

-- 
Charles DeRykus
to do

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: other ways to parse emails from html?

2013-01-31 Thread Charles DeRykus
On Thu, Jan 31, 2013 at 1:07 PM, Octavian Rasnita  wrote:
> From: "Jeswin" 
>
>
>> ...
>
>
>
>
> It depends what kind of emails you want to get from those web pages.
>
> If you want to get only and only the emails that appear in links, the most
> easier way is to use something like:
>
> #It will get the emails from links like:  href="mailto:n...@host.com";>E-mail
>
> use strict;
> use warnings;
> use LWP::Simple;
> use HTML::TreeBuilder;
>
> my $content = get( 'http://www.site.org/' );
> my $tree = HTML::TreeBuilder->new_from_content( $content );
>
> my @links = $tree->look_down( _tag => 'a', sub {
>$_[0]->attr('href') && $_[0]->attr('href') =~ /^\s*mailto:/;
> } );
>
> my @emails;
>
> for my $link ( @links ) {
>my $url = $link->attr('href');
>$url =~ s/^\s*mailto:\s*//;
>push( @emails, $link );
> }
>
> (Untested)  You should have the emails in @emails.

Variant of above:

use HTML::TreeBuilder 5.03;
use URI;

my $t = HTML::TreeBuilder->new_from_url( $some_url );

my @emails;
foreach my $link ( $t->look_down(_tag=>'a', href=>qr/^\s*mailto/) ) {
 my $url = URI->new( $link->attr('href') );
 push( @emails, $url->path );
}

>
>
> But if you want to get any e-mail from a page, no matter if it appears in a
> link or not, probably the easiest way would be to use regular expressions.
> Or search on CPAN if there is a module that does that easier.

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: trying to understand HTML::TreeBuilder::XPath

2013-01-28 Thread Charles DeRykus
On Mon, Jan 28, 2013 at 8:21 AM, Brandon McCaig  wrote:
> On Sat, Jan 26, 2013 at 06:16:14PM -0800, Jim Gibson wrote:
>> Better add periods to that regular expression character class:
>>
>>   if( $link =~ /mailto:([\w@.]+)/ ) {
>>
>> … or include everything up to but not including the second double-quote:
>>
>>   if( $link =~ /"mailto:([^"]+)/ ) {
>
> I've never used HTML::TreeBuilder::XPath, but I highly doubt that
> the attr method would return the quotes (and if it did, they
> could be single-quotes instead). It would probably be best to
> find a module that knows how to properly parse mailto URIs, but
> failing that I think that matching everything *from the
> beginning*[1] up to a literal '?' should suffice.
>
> [1] You may wish to tolerate leading white space too, but I'm not
> sure if that is valid.
>
> if($link =~ /^mailto:([^\?]+)/) {
> my $email = $1;
> ...
>
> Untested, but can't *possibly* fail. ;)

A module is a good idea since URI will parse a valid
mailto  and ignore leading whitespace. Note however
there may be multiple comma separated emails.

See: perldoc URI.

my $uri = URI->new($link);
if ( $uri->scheme eq 'mailto') {
 my $email = $uri->path;
 ...
}

--
Charles DeRykus

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: character setts in a regexp

2013-01-14 Thread Charles DeRykus
On Sat, Jan 12, 2013 at 12:56 PM, Charles DeRykus  wrote:
> On Fri, Jan 11, 2013 at 2:01 PM, Christer Palm  wrote:
>> Hi!
>>
>> I have a perl script that parses RSS streams from different news sources and 
>> experience problems with national characters in a regexp function used for 
>> matching a keyword list with the RSS data.
>>
>> Everything works fine with a simple regexp for plain english i.e. words 
>> containing the letters A-Z, a-z, 0-9.
>>
>> if ( $description =~ m/\b$key/i ) {….}
>>
>> Keywords or RSS data with national characters don’t work at all. I’m not 
>> really surprised this was expected as character sets used in the different 
>> RSS streams are outside my control.
>>
>> I am have the ”use utf8;” function activated but I’m not really sure if it 
>> is needed. I can’t see any difference used or not.
>>
>> If a convert all the national characters used in the keyword list to html 
>> type ”å” and so on. Changes every occurrence of octal, unicode 
>> characters used i.e. decimal and hex to html type in the RSS data in a 
>> character parser everything works fine but takes time that I don’t what to 
>> avoid.
>>
>> Do you have suggestions on this character issue? Is it possible to determine 
>> the character set of a text efficiently? Is it other ways to solve the 
>> problem?
>>
...

> #!/usr/bin/perl
> use strict;
> use warnings;
>
> binmode(STDOUT, ":utf8");
> $cosa = "my \x{263a}";
> print "cosa=$cosa\n";
>
> print "found smiley at \\b\n" if $cosa =~ /\b\x{263a}/;
> print "found smiley (no \\b)"  if $cosa =~ /\x{263a}/;
>
> The output:
> cosa=my ☺
> found smiley (no \b)
>

From: http://www.unicode.org/reports/tr18/#Simple_Word_Boundaries
---
Most regular expression engines allow a test for word boundaries (such
as by "\b" in Perl). They generally use a very simple mechanism for
determining word boundaries: one example of that would be having word
boundaries between any pair of characters where one is a
 and the other is not, or at the start and end of a
string. This is not adequate for Unicode regular expressions.
-

Based on the above, Perl's \b semantics appear to be "not adequate
for Unicode regular expressions" since, it doesn't address extended
code points of Unicode, only values in the alphanumeric range and
underscore.

So, you may possibly want to try a preceding space to delimit the
keyword

print "match" if "my \x{263a}"=~ / \x{263a}/;   # matches!
#print "match" if "my \b\x{263a}" =~ /\b\x{263a/;   # would not match

-- 
Charles DeRykus

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Line-oriented socket I/O using select()

2013-01-13 Thread Charles DeRykus
On Sun, Jan 13, 2013 at 3:03 PM, Vic Sage  wrote:
> I'm writing a multiplexed TCP-based server that reads "\n"-terminated strings 
> from clients and does something with them.  Since this is one process with 
> multiple client connections, it uses select() (or, actually, can_read from 
> IO::Select) to block until data has arrived from any client.
>
> It's my understanding that TCP does not preserve "message boundaries."  That 
> is, if a client writes:
>
> $sock->autoflush(1);
> print $sock "abel\n";
> print $sock "baker\n";
> print $sock "charlie\n";
>
> ... there are no guarantees about what will be returned from the server's 
> system buffer by sysread() when select() pops.  It could be "a", or "abel\n", 
> or "abel\nbak", etc.
>
> What I *want* is to block until an entire "\n"-terminated string [can that be 
> referred to as a "line"?]  can be retrieved from one of my clients.  I'm sure 
> I could work out the logic to maintain application-level buffers, but I 
> suspect I would merely be reinventing the wheel, one bug at a time :-).   
> What does the experienced Perl programmer - or socket-level programmer in 
> general - do in this situation?
>

I'm not experienced in heavy duty socket-level programming
but you may want to invest in learning POE:

  https://poe.perl.org

It's already refined many of the wheels you'll need and appears well
documented.

-- 
Charles DeRykus

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: character setts in a regexp

2013-01-12 Thread Charles DeRykus
On Fri, Jan 11, 2013 at 2:01 PM, Christer Palm  wrote:
> Hi!
>
> I have a perl script that parses RSS streams from different news sources and 
> experience problems with national characters in a regexp function used for 
> matching a keyword list with the RSS data.
>
> Everything works fine with a simple regexp for plain english i.e. words 
> containing the letters A-Z, a-z, 0-9.
>
> if ( $description =~ m/\b$key/i ) {….}
>
> Keywords or RSS data with national characters don’t work at all. I’m not 
> really surprised this was expected as character sets used in the different 
> RSS streams are outside my control.
>
> I am have the ”use utf8;” function activated but I’m not really sure if it is 
> needed. I can’t see any difference used or not.
>
> If a convert all the national characters used in the keyword list to html 
> type ”å” and so on. Changes every occurrence of octal, unicode 
> characters used i.e. decimal and hex to html type in the RSS data in a 
> character parser everything works fine but takes time that I don’t what to 
> avoid.
>
> Do you have suggestions on this character issue? Is it possible to determine 
> the character set of a text efficiently? Is it other ways to solve the 
> problem?
>
> /Christer
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>

On Fri, Jan 11, 2013 at 2:01 PM, Christer Palm  wrote:
> Hi!
>
> I have a perl script that parses RSS streams from different news sources and 
> experience problems with national characters in a regexp function used for 
> matching a keyword list with the RSS data.
>
> Everything works fine with a simple regexp for plain english i.e. words 
> containing the letters A-Z, a-z, 0-9.
>
> if ( $description =~ m/\b$key/i ) {….}
>
> Keywords or RSS data with national characters don’t work at all. I’m not 
> really surprised this was expected as character sets used in the different 
> RSS streams are outside my control.
>
> I am have the ”use utf8;” function activated but I’m not really sure if it is 
> needed. I can’t see any difference used or not.
>
> If a convert all the national characters used in the keyword list to html 
> type ”å” and so on. Changes every occurrence of octal, unicode 
> characters used i.e. decimal and hex to html type in the RSS data in a 
> character parser everything works fine but takes time that I don’t what to 
> avoid.
>
> Do you have suggestions on this character issue? Is it possible to determine 
> the character set of a text efficiently? Is it other ways to solve the 
> problem?
>

I'm not sure if this is related but the docs mention some character
and byte semantics overlap.

*** START perlunicode:
..As discussed elsewhere, Perl has one foot (two hooves?) planted in
each of two worlds: the old world of bytes and the new world of
characters, upgrading from bytes to characters when necessary. If your
legacy code does not explicitly use Unicode, no automatic switch-over
to characters should happen. Characters shouldn't get downgraded to
bytes, either. It is possible to accidentally mix bytes and
characters, however (see perluniintro), in which case \w in regular
expressions might start behaving differently (unless the /a modifier
is in effect). Review your code. Use warnings and the strict pragma.
*** END perlunicode


Perhaps, although not explicit,  this downgrading might potentially
impact \b as well as \w.   Here's an example which appears to
support this  since adding \b causes the match to fail.  (There may
workaround via the character properties mentioned in perlunicode)


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

binmode(STDOUT, ":utf8");
$cosa = "my \x{263a}";
print "cosa=$cosa\n";

print "found smiley at \\b\n" if $cosa =~ /\b\x{263a}/;
print "found smiley (no \\b)"  if $cosa =~ /\x{263a}/;

The output:
cosa=my ☺
found smiley (no \b)

-- 
Charles DeRykus

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: substitution: interpolate capture buffer into variable?

2012-12-26 Thread Charles DeRykus
On Wed, Dec 26, 2012 at 10:29 AM, Paul Johnson  wrote:
> On Wed, Dec 26, 2012 at 04:10:06PM +0100, gator...@yahoo.de wrote:
>> Hi,
>>
>> I would like to store regular expressions and substitution strings in
>> a hash variable. If a given string matches any of the stored patterns,
>> the corresponding substitution should be applied. What originally looked
>> trivial turned out to be quite a challenge, particularly if the
>> substitution string contains references to capture buffers.
>>
>> Here's a minimal example:
>>
>> my $rx=qr/^_(.*)/;
>> my $r='a_$1';
>> my $s="_bla_fasel_blub";
>> if ($s=~ /$rx/) { # pattern matches, apply substitution if you can
>> # hardcoded, it's trivial:
>> # $s =~ s/$rx/a_$1/;
>> # but how to interpolate the capture buffer? Not like this:
>> # eval '$s="$r"';
>> # eval { $s=$r };
>> # $s =~ s/$rx/$r/e;
>> }
>>
>> Can anybody think of a straightforward way to do this?
>
> This is a situation where string eval is warranted:
>
> eval "\$s =~ s/\$rx/$r/";

I'd recommend against the use of string eval  if at
all possible. There's the trusted input issue which
you cite but also additional complications if the
input does need to be inspected/laundered:
  See  perldoc -q taint

Also, you can usually arrange to avoid eval or
 s///ee totally with a  differently crafted regex.
See Timothy's post.  A "no eval" solution will be
faster too and you won't need to examine $@.

> ...
>  - there's no need to check if the pattern matches first, just attempt
>the substitution

It may be a good sanity check to do so though if you're always
expecting the substitution to succeed. Otherwise,
even though the eval works,  a failed pattern match will
fail silently. But you could still report failure by checking
the substitution return:

s/.../../ or carp "pattern failed";

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Help with a regex

2012-12-21 Thread Charles DeRykus
On Thu, Dec 20, 2012 at 11:39 PM, Feng He  wrote:
> Hello,
>
> I have a string like: dns\.support.dnsbed.com
> I want to translate it to a regular email address: dns.supp...@dnsbed.com
>
>
> if ($string =~ /^(.*?)(? my $user = $1;
> my $tld = $2;
> return $user . '@'. $tld;
>  }
>
> But this won't work correctly. I got:
> d...@support.dnsbed.com
>
> Where do I get wrong? Thanks.
>

A couple of like problems:

You probably had $string double quoted instead of
single quoted which later results in the \ being eaten.

Example:  $string = "dns\.support.dnsbed.com";

After perl parsing, the $string is now "dns.support.dnsbed.com"
and your regex produces the output you saw.

If, instead $string = "dns\\support.dsnbed.com", then your regex
output would be:  dns\.supp...@dnsbed.com

That's closer to what you want... one solution to the unwanted \
would be $user =~ tr/\\//d;

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Retry function?

2012-12-13 Thread Charles DeRykus
On Thu, Dec 13, 2012 at 8:09 AM, Alvin Ramos  wrote:
> Any one have any suggestions of a module/function/method to write a perl 
> script to try pinging a server then after the 3rd time to send an email? 
> Thanks in advance...

perldoc Net::Ping

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: How to display UTF-8 output to command shell in Win7?

2012-12-01 Thread Charles DeRykus
On Sat, Dec 1, 2012 at 10:06 PM, boB Stepp  wrote:
> On Sat, Dec 1, 2012 at 11:58 PM, Charles DeRykus  wrote:
>> On Sat, Dec 1, 2012 at 8:50 PM, boB Stepp  wrote:
>>>
>>> What I would like to do is make chcp 65001 the default behavior of the
>>> command console without having to either retype it manually or place
>>> it in each and every script for each time I open the command prompt.
>>> Secondarily, I would like to eliminate what appears to be Windows
>>> informational message of "Active code page: 65001".
>>
>>
>>  On the command line, I believe you just redirecto to nul:
>>
>>   chch 2>nul
>>
>> From a  perl program:  use the File::Spec sequence I showed earlier
>>
> I earlier tried this as you suggested, but it did not seem to work.
> Perhaps I am misunderstanding something?

Normally, it should.  chcp may be doing something with stderr
directly in which case you'll need to use backticks after all.

This seems to work:

 my $status = qx{chcp 2>nul};
 die "chcp error: $?" if $?;

-- 
Charles DeRykus



-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: How to display UTF-8 output to command shell in Win7?

2012-12-01 Thread Charles DeRykus
On Sat, Dec 1, 2012 at 9:58 PM, Charles DeRykus  wrote:

> ...
>
>  On the command line, I believe you just redirecto to nul:
>
>   chch 2>nul
 ^^^
     chcp

--
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: How to display UTF-8 output to command shell in Win7?

2012-12-01 Thread Charles DeRykus
On Sat, Dec 1, 2012 at 8:50 PM, boB Stepp  wrote:
> Hey Tim,
>
> On Sat, Dec 1, 2012 at 10:34 PM, timothy adigun <2teezp...@gmail.com> wrote:
>> Hi bOB,
>> Please check my comments below
>>
>
>> It is very possible, just in 3 steps.
>>
>>  Here is what you had always wanted to do:
>>   1. Open up your command Prompt, then
>>
>>   2. You will need to change your cmd font to "Lucida Console", because
>> other fonts don't contain all the codepoints.
>> So, to do this, Right-click on the bar of the cmd Prompt, click on
>> Properties, then on Fonts tab, select "Lucida Console",
>
> Based on my searching, I had already done steps 1) and 2). These
> change the default values of the command console.
>
>>
>> 3. Ordinarily, if you type "chcp" on the cmd Prompt, you will get this :
>> Active code page: 850
>> The current Active code. To display Unicode however, you will need to change
>> that to 65001.
>> So, you might change it by typing "chcp 65001" on your cmd Prompt or do it
>> in your Perl script, using a backtick.
>>
>>  Here is how your script now looks:
>>
>> use warnings;
>> use strict;
>> use utf8;
>>
>> `chcp 65001`;
>> binmode STDOUT, ":encoding(UTF-8)";
>> print "\x{03B1}\x{03C9}\n";
>
> If you recall my original posting, I essentially did what you just
> said in step 3) except that I used system() instead of the backticks


Yes, system()  would be preferable to backticks in void context.
To see why:

 perldoc -q "What's wrong with using backticks in a void context?"


.
> What I would like to do is make chcp 65001 the default behavior of the
> command console without having to either retype it manually or place
> it in each and every script for each time I open the command prompt.
> Secondarily, I would like to eliminate what appears to be Windows
> informational message of "Active code page: 65001".


 On the command line, I believe you just redirecto to nul:

  chch 2>nul

From a  perl program:  use the File::Spec sequence I showed earlier


> But as I said,
> unless you or someone else knows something different to do, there is
> no way to permanently change the default behavior of the command
> prompt on my system. Is it clear what I am actually asking?
>
> One thing you add above, "use strict;": I have not reached this in my
> book yet. Is this something you would recommend me to add to my
> scripts routinely?
>

   Yes, 'use strict;' has been a best practice for some time.
   See:  perldoc perlstyle

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: How to display UTF-8 output to command shell in Win7?

2012-11-29 Thread Charles DeRykus
On Thu, Nov 29, 2012 at 5:00 AM, timothy adigun <2teezp...@gmail.com> wrote:
> Hi,
> Please check my comments below:
>
> On Thu, Nov 29, 2012 at 8:55 AM, Charles DeRykus  wrote:
>>
>> On Wed, Nov 28, 2012 at 8:10 PM, boB Stepp  wrote:
>> > As I have mentioned in an earlier posting, I am working my way
>> > (slowly) through Learning Perl, 6th edition. In this edition it uses
>> > UTF-8 throughout. So I have been trying to make this happen in my
>> > Windows 7 Pro 64-bit environment.
>> >
>> > Currently the only way I have been able to display Unicode characters
>> > in the command console is as follows:
>> >
>> > #!/usr/bin/env perl -w
>> > use utf8;
>> >
>> > system "chcp 65001";
>
>  ...
> binmode STDOUT,':encoding(UTF-8)';## add this
  

Hmm,  why is that different?In 5.14 at least it makes no difference.

Both:binmode(STDOUT, ":utf8");
and: binmode STDOUT,':encoding(UTF-8)';

suppress the "Wide character..." warning. but neither suppresses
the "Active code page: 65001" output.

You could however do something like this to portably suppress that
output too:


use File::Spec;
...
my $null = File::Spec->devnull();
system("chcp 65001 2>$null");



>even when warnings is turned OFF, you will get the unwanted warning
>

Just a guess because I don't know what chcp is all about...
but it might be  informational rather than an actual warning.

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: How to display UTF-8 output to command shell in Win7?

2012-11-28 Thread Charles DeRykus
On Wed, Nov 28, 2012 at 8:10 PM, boB Stepp  wrote:
> As I have mentioned in an earlier posting, I am working my way
> (slowly) through Learning Perl, 6th edition. In this edition it uses
> UTF-8 throughout. So I have been trying to make this happen in my
> Windows 7 Pro 64-bit environment.
>
> Currently the only way I have been able to display Unicode characters
> in the command console is as follows:
>
> #!/usr/bin/env perl -w
> use utf8;
>
> system "chcp 65001";
> print "\x{03B1}\x{03C9}\n";
>
> This seems to do the job, but is inelegant. I would much rather prefer
> that the command console automatically default to displaying all text
> as UTF-8, but Googling has not found a solution for me. Does anyone
> know how to solve this?
>
> One other thing that bugs me is that if I have warnings turned on as
> above and actually print non-ASCII characters, then I get an unwanted
> warning. For instance, the above code gives me this output:
>
> Active code page: 65001
> Wide character in print at helloworld.pl line 5.
> αω
>
> Press any key to continue . . .
>
> Ideally, I would rather I did not get the first two lines of output.
> Is there a way to accomplish this and still have warnings turned on?
> (I understand that the first line is a consequence of my system
> command to turn on UTF-8.)
>
>

binmode STDOUT, ":utf8";


-- 
Charles DeRykus

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: hash help !

2012-11-15 Thread Charles DeRykus
On Thu, Nov 15, 2012 at 2:46 AM, jet speed
>  ...
>   I was able to build the hash, however the file contains approx 10,000
> entries. but while i print the hash i get only approx 1300 lines or
> key=>values.
>
>  i guess its because, the file has duplicate entries. example below
>
>   file.txt
>> 
>>
>22:5a => 10.00.00.00.aa.56.9b.7a
>22:5a => 10.00.00.00.aa.57.99.8a
>32:9c => 10.00.00.00.aa.46.9b.33
>a2:cc => 10.00.00.00.aa.5a.9b.63
>a5:cc => 10.00.00.00.aa.5a.9b.63
>b2:cc => 10.00.00.00.aa.5a.9b.63
>
> How do i build all the entries into hash including the duplicates on both
> sides keys and values.

One possible way:

DB_File has a BTREE file type (with the R_DUP setting and
the 'seq' API method)  that enables storing/retrieving dup's.
There's a full example in the docs.

See: perldoc DB_File.

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: hash help !

2012-11-14 Thread Charles DeRykus
On Wed, Nov 14, 2012 at 9:05 AM, jet speed  wrote:
> Hi
> Is there a way, i can build an %hash from a file as Input. Appreciate you
> help with this.
>
> file.txt
> 
>
> 22:5a => 10.00.00.00.aa.56.9b.7a
> 32:9c => 10.00.00.00.aa.46.9b.33
> a2:cc=> 10.00.00.00.aa.5a.9b.63

Assuming no anomalies/surprises in file.txt:

use File::Slurp;
use strict;
use warnings;

my @lines = read_file( 'file.txt', chomp=>1 );
my %hash =  map { split( /\s*=>\s*/,$_ ) } @lines;

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Is CGI module has bug for Win7?

2012-10-26 Thread Charles DeRykus
On Fri, Oct 26, 2012 at 10:25 AM, Andy Bach  wrote:
> On Fri, Oct 26, 2012 at 5:27 AM, Praveen Kumar
>  wrote:
>> , build : 12 randompassil.com --> This is what I am getting
>>
>> User : praveenku...@gmail.com, Password : randompass, build : 12  -->
>
> Yeah, stack them up and:
>
> User : praveenku...@gmail.com
> , Password : randompass
> , build : 12  -->
>
> That is:
> User : praveenku...@gmail.com\r, Password : randompass\r, build : 12\r  -->
>
> your chomps are removing \n (newline) from the input but not \r
> (carriage return) - Perl normally does that correctly by deciding
> which OS you're on.
>
> Hmm:
> http://www.perlmonks.org/bare/?node_id=55540
>
> Seems to say that Win32 CGI.pm sets binmode on STDIN (and STDERR,
> STDOUT).  Does adding:
> $/ = "\r\n";
>
> after
> use CGI;

Or, just:

   binmode  STDIN,  ":crlf";

This is Perl's layer to implement DOS/Windows like CRLF line endings.
See: perldoc perlio

-- 
Charles DeRykus

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Wide character in print at D:/Perl/lib/WWW/Mechanize.pm line 2044

2012-10-23 Thread Charles DeRykus

On 10/22/2012 4:31 AM, Ganesh Babu N wrote:


I am using WWW::Mechanize to fetch the content from the web. when I
used save_content method, I am getting the above said error. In the
output the character is not displaying properly. I need to encode the
HTML content to UTF-8 so that the character looks correct.

I have modified the Mechanize.pm @ line no. 2042 to open( my $fh,
'>:utf8', $filename ). But I am not getting the desired output.

Please help in getting the $mech->content in utf-8 format.



Try $mech->decoded_content instead of $mech->content.

HTH,
Charles DeRykus


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: how to do a reference to a func in Math::Trig

2012-06-24 Thread Charles Smith
Thank you.  The useful note about CORE, in particular, is new to me.

cts

--- On Sun, 6/24/12, Rob Dixon  wrote:

> From: Rob Dixon 
> Subject: Re: how to do a reference to a func in Math::Trig
> To: "Perl Beginners" 
> Cc: "Charles Smith" 
> Date: Sunday, June 24, 2012, 11:53 AM
> On 24/06/2012 19:51, Rob Dixon
> wrote:
> > 
> > or by aliasing the current package's 'sin' and 'cos'
> subroutines with
> > the CORE functions:
> > 
> >      use strict;
> >      use warnings;
> > 
> >      use Math::Trig;
> > 
> >      BEGIN {
> >        no warnings 'once';
> >        *sin = \&CORE::sin;
> >        *cos = \&CORE::cos;
> >      }
> > 
> >      for my $func (qw/ sin cos tan /) {
> >        my $f = \&$func;
> >        print $f->(pi/4), "\n";
> >      }
> > 
> > which IMO is the tidiest, and certainly the most
> efficient.
> 
> Please note that the 'no warnings' is necessary only for
> runtime typeglob assignments. This also works fine, and is
> even neater.
> 
>     use strict;
>     use warnings;
> 
>     use Math::Trig;
> 
>     BEGIN {
>       *sin = \&CORE::sin;
>       *cos = \&CORE::cos;
>     }
> 
>     for my $func (qw/ sin cos tan /) {
>       my $f = \&$func;
>       print $f->(pi/4), "\n";
>     }
> 
> -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
> 
> 
>

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: how to do a reference to a func in Math::Trig

2012-06-23 Thread Charles Smith
Thank you, that was the clue I needed!  This now works for me:

...
$f = $opts{f} || "sin";
...
$f = "Math::Complex::$f";
...
print eval ($amplitude) * (&$f (2 * pi * $i/$n) + eval ($dc))."\n";

and so I can use this, my "siggen" pgm with gnuplot:

plot   "<(./siggen  -f cos  -p 2 -n66  )" lc 1

to get a nice curve.

Unfortunately, though, I was only able to get it to work as symbolic reference. 
 First I tried:

$f = \&Math::Complex::$func;

Scalar found where operator expected at ./siggen line 194, near 
"&Math::Complex::$func"
(Missing operator before $func?)
syntax error at ./siggen line 194, near "&Math::Complex::$func"

I also tried:

$f = eval (\&Math::Complex::$func)

but that didn't help.

But that's all unimportant, because my pgm works now,
thank you.

cts


--- On Sat, 6/23/12, Ron Bergin  wrote:

> From: Ron Bergin 
> Subject: Re: how to do a reference to a func in Math::Trig
> To: "Charles Smith" 
> Cc: beginners@perl.org
> Date: Saturday, June 23, 2012, 3:28 PM
> Charles Smith wrote:
> 
> [snip]
> >
> > But this pgm fails:
> >
> > #!/usr/bin/env perl
> > use Math::Trig;
> > my $a = \&Math::Trig::cos;
> > &$a(0);
> >
> > Undefined subroutine &Math::Trig::cos called at
> modfunctor line 7.
> >
> 
> The cos sub is defined in Math::Complex, which Math::Trig
> loads.
> 
> Try this:
> 
> use strict;
> use Math::Trig;
> 
> my $cos = \&Math::Complex::cos;
> print $cos->(0);
> 
> 
> 
> -- 
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
> 
> 
> 

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: how to do a reference to a func in Math::Trig

2012-06-23 Thread Charles Smith
Hello Shawn, thank you for answering.

I'm sorry, I was a bit sloppy with my example and so maybe unclear about my 
question ...

It's not about the precise syntax of getting a reference to a subroutine, but 
rather a subroutine in a module.

For example, this pgm is clear:

#!/usr/bin/env perl
sub b { print "hello world\n"; }
my $a = \&b;
&$a;

prints
hello world

But this pgm fails:

#!/usr/bin/env perl
use Math::Trig;
my $a = \&Math::Trig::cos;
&$a(0);

Undefined subroutine &Math::Trig::cos called at modfunctor line 7.


(and other tested variations, too numerous to list here)

e.g.:

my $a = \&cos;
Undefined subroutine &main::cos called at modfunctor line 8.

my $a = "cos";   # symbolic ref
Undefined subroutine &main::cos called at modfunctor line 8.

my $a = "Math::Trig::cos";
Undefined subroutine &Math::Trig::cos called at modfunctor line 9.


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




how to do a reference to a func in Math::Trig

2012-06-23 Thread Charles Smith
Hi,

I'm experimenting with Math::Trig and would like to be able to pass the 
function in as a parameter:

  $f = $opts{f} || &sin;

  ...
  &$f($w);

Undefined subroutine &main::sin called at (eval 
9)[/usr/lib/perl5/5.14.2/perl5db.pl:640] line 2.


I have also tried:

  $f = &Math::Trig::sin;   
Undefined subroutine &Math::Trig::sin called at (eval 10)...
  $f = \&sin;# just delays the problem

  etc.

Can anyone tell me how to take a reference to func in a module?

TIA
cts 

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




can't post to perl.beginners

2009-11-03 Thread Charles DeRykus
Hello,

I subscribed to perl.beginners via Google groups but none of my posts
get through

Can you help or suggest what might be amiss?

-- 
Charles DeRykus


great new installation package - how to override /usr/lib/perl5/site_perl/5.8.8?

2009-10-05 Thread Charles Smith
I'm trying to install UR-v0.12 - and encountered a great wizard.  But I don't 
have root access on my machine.  I get

  You are not allowed to write to the directory '/usr/lib/perl5/site_perl/5.8.8'

even though I'd entered

  Your choice:  [] PREFIX=~/lib/perl


Can somebody please explain to me how I can use ~/lib/perl instead of something 
in superuser areas?


  


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Help with passing arrays to a Perl subroutine

2007-11-02 Thread Charles
On Nov 1, 1:37 pm, [EMAIL PROTECTED] (Jl Post) wrote:
> On Nov 1, 9:35 am, [EMAIL PROTECTED] (Charles) wrote:
>
>
>
> > I have module from CPAN named Graph. I have created a subroutine for
> > this to pass in two arrays; x-axis and y-axis into my Graph subroutine
> > i.e. ; &graph( @Xvalues,  @Yvalues );
>
> > My confusions is: in my subroutine, I cannot treat the two parameters
> > (arrays) as separate parameters.
>
> Dear C. Carson,
>
>That's right.  InPerl, you usually cannot treat two arrays as
> separate parameters.  As a result, your line:
>
>   graph( @Xvalues,  @Yvalues );
>
> is functionally equivalent to the following two lines:
>
>   my @array = ( @Xvalues, @Yvalues );
>   graph( @array );
>
> which I'm guessing is not what you meant.
>
>To do what you want, you need to pass in two scalar values as
> parameters (each representing one array), and then extracting the
> arrays out in the graph() function.  For example, you'd call your
> graph() function like this:
>
>   graph( [EMAIL PROTECTED], [EMAIL PROTECTED] );
>
> The '\' character (in front of both arrays) returns a scalar reference
> to its array, which is then sent into the graph() function.
>
>However, in your graph() function $_[0] and $_[1] will not be set
> to the arrays, but rather the references to the arrays.  You must do
> something like this in your graph() function to de-reference them:
>
>   sub graph
>   {
>  my @Xvalues = @{ $_[0] };  # remember to use "my"!
>  my @Yvalues = @{ $_[1] };  # remember to use "my"!
>
>  # The @Xvalues and @Yvalues arrays are now set to what you
> want.
>
>  # (The rest of your code goes here.)
>   }
>
>I hope this helps, C. Carson.
>
>-- Jean-Luc

Thank you so much for your help! I will try this and let you know.


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




Help with passing arrays to a Perl subroutine

2007-11-01 Thread Charles
Help

Three days of head-banging the Boss has my walking papers if I
don't "get'er done"!

I have module from CPAN named Graph. I have created a subroutine for
this to pass in two arrays; x-axis and y-axis into my Graph subroutine
i.e. ; &graph( @Xvalues,  @Yvalues );

My confusions is: in my subroutine, I cannot treat the two parameters
(arrays) as separate parameters. Therefore both arrays @Xvalues
@Yvalues are seen as one big string of numbers when I pass them.
everything is one one axis, the x-axis.

Can anyone out there in PERL land help out? I have tried $_[0].,
but it only returns the first element and so on of the array in the
first parameter passed @Yvalues.


Thanks,

C Carson


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




Accessing hash within an array of hashes

2007-08-07 Thread Charles J Gillan

I have a problem with extracting an individual hash from an array of
hashes. I can't work out, or find elsewhere, the syntax for this.

Code as follows:

 devices_array_oH  is set up as array of hashes

I want to loop over all hashes in the array and to print the key value pairs for
each hash.

I have tried the following but get run-time errors:

   my($num_devices, $idevice);

$num_devices = scalar (@devices_array_oH) ;

for ($idevice=0; $idevice < $num_devices; $idevice++)
  {
   my (%device_hash, $itemp, $key);

   $itemp = $idevice + 1;

   #
   #--- Extract one element of array to local hash
   #

   %device_hash = $devices_array_oH[$idevice];   <---   Flagged as 
run-time error:

   Reference found 
where even size list expected

   print " Details of device $itemp: ";
   print "\n\n";

   foreach $key (keys(%device_hash))
 {
  print ("   $key  \t  $device_hash{$key} \n"); < Flagged 
as run-time error
 }   use of 
un-initialized value in concatenation
 Presumably 
due to above

   print "\n\n";
   print " * End of details for all devices ";
   print "\n\n";
  }

Just can't figure it out - any suggestions.

Thanks,

Charles.






RE: my, my...

2006-12-15 Thread Charles K. Clarkson
Jorge Almeida <mailto:[EMAIL PROTECTED]> wrote:

:   #!/usr/bin/perl -w
:   use strict;
:   use diagnostics;
:   my $a="27";
:   doit();
:   sub doit{
:   print "$a\n";
:   }
: 
: The output of this program is:
: 27
: 
: Just what I would expect if line 4 had "our" instead of "my".
: What am I missing?

$a, in this case, is a file-scoped lexical. It is available
anywhere in the file. Sometimes a file scoped lexical is called
a global variable, though that can be confusing because global
has other meanings as well.

It is usually best to avoid using variables which are not
local to a sub routine inside a sub routine, though there are
cases where this it is desirable and good programming practice.


HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.


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




RE: reg exp continued need pulled from reference

2006-12-13 Thread Charles K. Clarkson
Derek B. Smith <mailto:[EMAIL PROTECTED]> wrote:


: I then tried

Try something simpler, not more complex. Test this case.

my @hosts = ( 'sun' );
$worksheet->write_col( 'A2', [EMAIL PROTECTED], $sheet_format );


If it fails testing then there may be a problem with
write_col() or with the setup for the object $worksheet.

If it does test okay then the problem may be in the
data manipulation just before the call to write_col().



HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.


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




RE: Conditional sorting across two arrays

2006-12-12 Thread Charles K. Clarkson
Rinku Mahesh <mailto:[EMAIL PROTECTED]> wrote:

:   If the above explaination is confusing I'm looking for a way
: where every element of an array can be mapped to corresponding
: element of another array and as a whole both the arrays require
: a sorting w.r.t. 2nd array.

M.J. Dominus wrote three slides about an Indirect Sort which
you may find helpful. He's using two arrays of names. One for
first names, one for last names. Basically, the idea is to sort
the array indexes and then apply the sorted indexes to each array
using an array slice. (I don't know if he's right about those APL
folks.)

http://perl.plover.com/yak/hw2/samples/slide003.html


In your case, you need a numerical comparison (<=>) on both
arrays as opposed to a string comparison (cmp). You also require
that ties be sorted on the other array. That can be performed
within the sort. One thing I like about sorting indexes is that
you can save the sorts.

use strict;
use warnings;

# Test data
my @unique= ( 66, 23, 44, 11, 900, 1009 );
my @occ_count = (  2, 77, 22,  2,  77,   29 );

# Sort in ascending order, ascending order
# Use reverse for descending order, descending order
my @ascending_indexes =
sort {
$occ_count[$a] <=> $occ_count[$b]
||
   $unique[$a] <=> $unique[$b]

} 0 .. $#occ_count;

# Sort in descending order, ascending order
# Use reverse for ascending order, descending order
my @descending_indexes =
sort {
$occ_count[$b] <=> $occ_count[$a]
||
   $unique[$a] <=> $unique[$b]

} 0 .. $#occ_count;


# Reports
print "Ascending sort then ascending sort:\n\t";
printf '%5d', $_ foreach @occ_count[ @ascending_indexes ];
print "\n\t";
printf '%5d', $_ foreach @unique[ @ascending_indexes ];
print "\n\n";

print "Ascending sort then descending sort\n\t";
printf '%5d', $_ foreach @occ_count[ reverse @descending_indexes ];
print "\n\t";
printf '%5d', $_ foreach @unique[ reverse @descending_indexes ];
print "\n";

print "Descending sort then descending sort:\n\t";
printf '%5d', $_ foreach @occ_count[ reverse @ascending_indexes ];
print "\n\t";
printf '%5d', $_ foreach @unique[ reverse @ascending_indexes ];
print "\n\n";

print "Descending sort then ascending sort\n\t";
printf '%5d', $_ foreach @occ_count[ @descending_indexes ];
print "\n\t";
printf '%5d', $_ foreach @unique[ @descending_indexes ];
print "\n";

__END__

For larger arrays, you might want to transform one array
first.


HTH,

Charles K. Clarkson
--
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.


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




RE: CYGWIN Uninstall

2006-12-10 Thread Charles K. Clarkson
Charith Hettige <mailto:[EMAIL PROTECTED]> wrote:

: And I am sorry if I caused any inconvenience by posting
: this as I thought people will be help full rather than
: point out what this mailing list is and what it is not.

Wow! That's a terrible apology. Rewrite it and try
being just a little contrite.


Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.


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




RE: Hi, how to extract five texts on each side of an URI? I post my own perl script and its use.

2006-11-11 Thread Charles K. Clarkson
Hui Wang <mailto:[EMAIL PROTECTED]> wrote:

: Can anybody tell me how to improve the running speed of this
: program? Thanks.

I don't know if this is faster, but it is a more accurate
solution. Your submitted code failed under some untested
circumstances. I created another page similar to the CPAN page you
used and fed it more complicated tests.

Chakrabarti placed relevance on distance from the link. I
changed your report to reflect this relevance. Instead of
squashing all text together, it now shows a report of text token
relevance. This change allowed me to test more thoroughly as well.
Here is the sample report for one link with multiple texts inside
the anchor.

http://www.clarksonenergyhomes.com/scripts/index.html
-5: 3401 MB 280 mirrors
-4: 5501 authors 10789 modules
-3: Welcome to CPAN! Here you will find All Things Perl.
-2: Browsing
-1: Perl modules
 0: Perl
 0: scripts
+1: Perl binary distributions ("ports")
+2: Perl source code
+3: Perl recent arrivals
+4: recent
+5: Perl modules

You can find the modified code here (for a short time):

Script: http://www.clarksonenergyhomes.com/chakrabarti.txt
Module: http://www.clarksonenergyhomes.com/chakrabarti.pm


HTH,

Charles K. Clarkson
--
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.



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




RE: Hi everyone, how to extract five texts on each side of an URI? I post my own perl script this time.

2006-11-09 Thread Charles K. Clarkson
Hui Wang <mailto:[EMAIL PROTECTED]> wrote:

: I can make my program do its job at last, but it runs
: slowly. Can anybody tell me how to improve the running
: speed of this program?

You only provided the module. Can you supply a
working example? Something we can actually run?

HTH,

Charles K. Clarkson
--
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts. 


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




RE: Conversion of Hex bytes to binary and vice versa

2006-11-09 Thread Charles K. Clarkson
Dharshana Eswaran <mailto:[EMAIL PROTECTED]> wrote:

: The desired output should look like the following:
: 
: 0x0a => 1010
: 0x23 => 00100011
: 
: Can anyone suggest me for the same?

Read perlfaq4:
  How do I convert between numeric representations/bases/radixes?



HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.


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




RE: Worse than just a beginner

2006-10-24 Thread Charles K. Clarkson
Brian <mailto:[EMAIL PROTECTED]> wrote:

: I'm wondering if someone can do me an enormous favour and
: write a cgi for me please, I just can't get my head around
: the books I have, they might just as well be written in
: Klingon.

You want us to feed you for a day?

Think about what needs to be done. What are the steps
needed to perform the actions to get the results you want?
Here's an example.

1. Get numerical user input.
2. Divide input from step 1 by 25 and keep the remainder.
3. Use the result from step 2 as an index into a string.
4. ...


Notice that my algorithm does not contain elements of a
specific solution. These steps could equally apply to VB, C#,
Java or Perl.

Once you have listed all the steps needed to describe the
problem then you can apply a specific solution. Look at each
step and solve only that step. Solutions are a lot easier if
you break them down into more manageable pieces first.

BTW, You don't have to solve them in the order they will
be used. Solve the easiest one first, then the next and so
on.

Look at step 2 above. Repeated subtractions gets you a
remainder. Now you have a solution for the remaining value.
Try to solve the rest yourself. Come back here when you get
stuck solving a step.

print 1 % 25, "\n";
print 30 % 25, "\n";
print 300 % 25, "\n";
print 1234 % 25, "\n";
print 60001 % 25, "\n";



HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.


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




RE: Jumping to inner loops

2006-10-24 Thread Charles K. Clarkson
Luba Pardo <mailto:[EMAIL PROTECTED]> wrote:

: Example: once that the element h=0 from arra1 is found in
: array2, then move to the inner loop for h to become h+2
: and not h+4. Then when the 4 consecutive elements in the
: array 1are found in the array 2, then make h= h+4 in the
: array1. Elements in the other array should move also
: every 4 elements.

Can you explain that better? It really makes very
little sense. Ignore the script and just explain each step
you wish to take. Forget about h and k and the inner and
outer loop, just explain what you are trying to accomplish.


HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.


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




RE: file parsing program -help

2006-10-17 Thread Charles K. Clarkson
I BioKid <mailto:[EMAIL PROTECTED]> wrote:

: I need a help to write a tricky perl script

This is not all that tricky to accomplish. Break the problem
into parts and solve each part. You have two main sections.
Searching cluster.txt for 100% and deleting corresponding records
from data.txt.


You can write the script in a number of ways, but try writing
the deletion section first. Given a gi number, delete a record in
data.txt. You'll probably do something like this.

- Open the file,
- Split the file by records,
- Search record for gi number field,
- Delete that record on the disk, and
- Close the file.


There's nothing tricky about that. Each of those steps is a
fairly trivial task. Some steps can be done in one line of perl
code. Here are some steps for the first sections.

- Open the file,
- Split the file by records,
- Search record for 100% field,
- Locate gi number,
- Delete that record in data.txt, and
- Close the file.

There's nothing tricky about that either. In fact, many of
those steps are the same as the one's above. Perl is an excellent
language choice for coding this type of application.

HTH,

Charles K. Clarkson
--
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

Don't tread on my bandwidth. Trim your posts.


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




RE: nice regular expression

2006-10-13 Thread Charles K. Clarkson
I.B. wrote:

: unfortunately I have to use regex to solve this problem.

Why do you have to use a regex?



Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

Don't tread on my bandwidth. Trim your posts.


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




RE: Modules for printing the content of an array

2006-10-11 Thread Charles K. Clarkson
Rob Coops wrote:

: Simply do this in your perl script:
: *use Data::Dumper;*
: *print Dumper @huge_array;*

For the archives:

Those asterisks (*) are for emphasis. They are not
actually in the code. Arrays and hashes can also be
dumped using a reference. I find a reference more
aesthetically pleasing.

use Data::Dumper 'Dumper';

print Dumper [EMAIL PROTECTED];


HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

Don't tread on my bandwidth. Trim your posts.


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




RE: need to parse and verify certain content..

2006-10-11 Thread Charles K. Clarkson
Vishwanath Chitnis wrote:

: is there any other way other than above mentioned to do this?

How can we possibly tell with only those lines?

Show more code. Something we can run that will illustrate
your problem.


HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

Don't tread on my bandwidth. Trim your posts.


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




Re: iterate through and array?

2006-10-10 Thread Charles Farinella

Tom Phoenix wrote:


It's hard to say for sure why it's not working, without seeing what
you're trying to do. But maybe you want to use the 'last' operator to
exit the foreach once you find a match? 'last' is documented in the
perlfunc manpage.


I believe that's just what I'm looking for, thanks so much.  :-)



Hope this helps!

--Tom Phoenix
Stonehenge Perl Training




--
----
Charles Farinella
Appropriate Solutions, Inc. (www.AppropriateSolutions.com)
[EMAIL PROTECTED]
voice: 603.924.6079   fax: 603.924.8668


--
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   5   6   7   8   9   >