Re: https://metacpan.org/pod/OpenOffice::OODoc

2024-01-28 Thread Jim Gibson via beginners
Check out the OpenOffice::OODoc module on CPAN:
<https://metacpan.org/pod/OpenOffice::OODoc::Intro>

The documentation is a little sparse, especially with regard to “spreadsheet” 
mode, and I don’t have Libre Office on my system to test it out, but the 
following code produces an ods file that can be opened by Microsoft Excel with 
the expected content on my Mac Pro running perl version 5.34.3:

#!/opt/local/bin/perl
use strict;
use warnings;

use OpenOffice::OODoc;

my $spreadsheet = odfDocument(
file => "spreadsheet.ods",
create => "spreadsheet",
);

$spreadsheet->appendTable("MyTable",6,4);
$spreadsheet->cellValue("MyTable",2,1,"New value");
$spreadsheet->save();



> On Jan 28, 2024, at 8:08 AM, hw  wrote:
> 
> On Thu, 2024-01-25 at 20:28 -0600, Mike wrote:
>> It can be done with a Perl module:
>> https://unix.stackexchange.com/questions/723650/editing-libreoffice-calc-spreadsheets-in-the-terminal
>> 
>> I have not tested that.
> 
> I do not want to edit spreadsheets in a terminal.  There's some other
> software for that.
> 
> I'm looking for something similar to Excel::Writer::XLSX, mainly to
> automatically export database tables to spreadsheets from perl
> programs in ods format rather than in xlsx format.
> 
> 
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
> 
> 

Jim Gibson
j...@gibson.org




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




Re: help with making an sftp connection

2023-04-16 Thread Jim Gibson via beginners
Perl has a repository of user-submitted modules called Comprehensive Perl 
Archive Network (CPAN). Net::SFTP::Foreign can be installed from there, and it 
looks like a good candidate, as does Net::SFTP. The two modules use different 
methods for invoking the SFTP protocol. I would try one and, if that doesn’t 
work, the other. You can also search CPAN for other FTP and SFTP modules. Most 
modules come with their own documentation and sample code. See this link for 
Net::STFP::Foreign: 

<https://metacpan.org/pod/Net::SFTP::Foreign>

Try what that gives you, and come back here if you have any specific questions 
or problems. It is always good to give it a try for yourself before asking for 
help. Post what you try.


> On Apr 16, 2023, at 2:40 PM, Brent Wood via beginners  
> wrote:
> 
> Hi,
> 
> I'm not a perl coder, (though have written a few very simple Perl scripts 
> when necessary) but now I need to write a Perl script to transfer specified 
> files from one computer to another. I have scribbled out a script a while 
> back using FTP, but now need to use SFTP. I can re-use most of the old FTP 
> code/logic, but need some help to make the actual connection.
> 
> It is a secure (no external connectivity) network, with no public/private key 
> security available, so authentication just via user/password
> 
> Some Googling for how I might do this in Perl has thrown up several 
> possibilities, more confusing than informative, so I'm not sure how to best 
> do this.
> 
> It looks like Net::SFTP::Foreign might best fit my needs, but I'm open to 
> suggestions.
> 
> 
> Advice or a code snippet on how to make the connection should be enough, and 
> much appreciated!!
> 
> 
> 
> Thanks,
> 
> Brent Wood

Jim Gibson
j...@gibson.org




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




Re: A Regular Expression Problem in Perl 5.28

2023-03-29 Thread Jim Gibson via beginners
On Mar 28, 2023, at 3:00 PM, Martin McCormick  wrote:
> 
> Uri Guttman  writes:
>> yes, but he kept the {5,} repeat count. so i just kept it too.
> 
> Now that I know how this works, I will probably change to
> {4,} as this would match 4 or more digits.  From reading the
> documentation, {4} means 4 and only 4.  {4,6} means 4 but nothing
> else except 6. {N,} means N as a low limit but any number higher.

\d{4,6} means match either 4, 5, or 6 successive number digits.

Here is the spec from perldoc perlretut:

*   "a{n,m}" means: match at least "n" times, but not more than "m" times.


Jim Gibson
j...@gibson.org




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




Re: Can use perl for download photos from facebook?

2022-03-20 Thread Jim Gibson
On Mar 20, 2022, at 7:28 AM, William Torrez Corea  wrote:
> 
> Ready, the result is it:
> 
> wget 
> https://scontent.fmga3-1.fna.fbcdn.net/v/t39.30808-1/274490608_3202483196693292_7724900589789523726_n.jpg_n.jpg


You’ve put an extra “_n.jpg” at the end of that URL because you captured the 
whole URL and then added that string. That is not what you want to do, but if 
you take off the extra piece, it still doesn’t work.

It is best, when trying to automate something, to ensure that you can do the 
thing manually first.

> When i try download a file:
> 
> --2022-03-20 08:27:41--  
> https://scontent.fmga3-1.fna.fbcdn.net/v/t39.30808-6/276012480_335659911953943_8504688182854120580_n.jpg_n.jpg
> Resolving scontent.fmga3-1.fna.fbcdn.net (scontent.fmga3-1.fna.fbcdn.net)... 
> 186.77.250.145
> Connecting to scontent.fmga3-1.fna.fbcdn.net 
> (scontent.fmga3-1.fna.fbcdn.net)|186.77.250.145|:443... connected.
> HTTP request sent, awaiting response... 403 Forbidden
> 2022-03-20 08:27:41 ERROR 403: Forbidden.
> 
> On Sun, Mar 20, 2022 at 7:45 AM Mike  wrote:
> 
> I don't use FB at all, but it's clear they spend a lot of their 
> resources obfuscating their website.  They provide a tool for 
> backing up your FB wall, or whatever it is called, but the tool 
> is not effective and reliable.  I'm sure there are people overcoming 
> this obfuscation, and then FB changes their site to obfuscate it again.
> 
> Here is one example of people overcoming the FB obfuscation, and then 
> FB changes their site to obfuscate it again:
> https://gist.github.com/zmwangx/6bb9ddb5d904b7275c62
> 
> I don't use FB because I don't like their rules.
> 
> 
> Mike
> 
> 
> On 3/19/22 22:25, William Torrez Corea wrote:
>> So, friend?
>> 
>> On Sat, Mar 19, 2022 at 8:23 PM Adam Hopkins  
>> wrote:
>> I mean the Facebook.html file that you are scanning
>> 
>> On Sat, Mar 19, 2022 at 9:17 PM William Torrez Corea  
>> wrote:
>> Here is the short code:
>> 
>> https://gist.github.com/adipasquale/2217595
>> 
>> 
>> 
>> On Sat, Mar 19, 2022 at 8:10 PM Adam Hopkins  
>> wrote:
>> Did you download Facebook.html and already have it sitting on your computer?
>> 
>> Can you upload that to a gist and share it here?
>> 
>> On Sat, Mar 19, 2022 at 8:48 PM William Torrez Corea  
>> wrote:
>> I have a short code:
>> 
>> #!/usr/bin/perl;
>> @ARGV = ("Facebook.html");
>> while(<>){
>> while(/(http[a-z\-\.0-9:\/]*\w*)_a.jpg/g){
>> print "wget $1_n.jpg\n";
>> }
>> }
>> 
>> But the result expected is null. I don't know why. 
>> 
>> On Sat, Mar 19, 2022 at 7:21 AM Jim Gibson  wrote:
>> Check out the LWP library of modules on CPAN:
>> 
>> <https://metacpan.org/pod/LWP>
>> 
>> > On Mar 19, 2022, at 6:07 AM, William Torrez Corea  
>> > wrote:
>> > 
>> > I have an idea from the program but I don't know where to start.  
>> > 
>> 
>> Jim Gibson
>> 
>> 
>> 
>> 
> 
> 
> 
> -- 
> With kindest regards, William.
> 
> ⢀⣴⠾⠻⢶⣦⠀ 
> ⣾⠁⢠⠒⠀⣿⡁ Debian - The universal operating system
> ⢿⡄⠘⠷⠚⠋⠀ 
> https://www.debian.org
> 
> ⠈⠳⣄ 
> 

Jim Gibson




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




Re: Can use perl for download photos from facebook?

2022-03-20 Thread Jim Gibson
On Mar 19, 2022, at 7:17 PM, William Torrez Corea  wrote:
> 
> Here is the short code:
> 
> https://gist.github.com/adipasquale/2217595
> 

The regular expression in that program is not valid. You are using brackets […] 
incorrectly. The pattern [a-z] will match exactly one character in the range 
a-z. The pattern [a-z\/\.] will match one character in the range a-z or the 
backslash character ‘\’ or the forward slash character’/‘ or the period 
character ‘.’. Inside brackets you do not need to escape special characters, 
and if you want to match the ‘-‘ character, put it at the beginning or ending 
of the pattern string, e.g. [a-z-] will match a-z or ‘-‘.

Here is a regular expression that should do what you want:

while ( /(https?:\/\/\S*?\.jpg)/g ) {

Here is another one that uses the m{} operator so you don’t have to escape the 
‘/‘ characters and the /x modifier to allow you to insert whitespace and 
comments into the regular expression to make it more readable:

while ( m{ ( https?:// \S*? .jpg ) }xg ) {

Either of these finds 47 links to .jpg files in your data document:

https://scontent.fmga3-1.fna.fbcdn.net/v/t39.30808-1/274490608_3202483196693292_7724900589789523726_n.jpg
...
   
Jim Gibson




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




Re: Can use perl for download photos from facebook?

2022-03-19 Thread Jim Gibson
Check out the LWP library of modules on CPAN:

<https://metacpan.org/pod/LWP>

> On Mar 19, 2022, at 6:07 AM, William Torrez Corea  
> wrote:
> 
> I have an idea from the program but I don't know where to start.  
> 

Jim Gibson




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




Re: use string in "use"

2020-12-14 Thread Jim Gibson
I have not used it myself, but the ‘if’ module allows one to load modules 
conditionally:

use if CONDITION, MODULE => ARGUMENTS;

See ‘perldoc if’ for more details.


> On Dec 14, 2020, at 7:23 AM, Gary Stainburn  
> wrote:
> 
> I've written my first re-usable modules in Perl, and all goes well. However, 
> I want to know if / how I can use a string variable in the 'use' clause.
> 
> In PHP I have a simple system of turning on/off debugging and version 
> control.  Any file *1.html is development version.  I then have
> 
> $DEBUG=(preg_match('/1.htm/',$_SERVER['REQUEST_URI'])) ? '1' : '';
> include_once("sql$DEBUG.inc");
> include_once("security$DEBUG.inc");
> 
> This way I have a live and a development version of every HTML and every inc 
> file, and putting any one file is simply a case of copying that file over.
> 
> I'm looking to replicate  this in Perl.  How can I do the following?
> 
> #!/usr/bin/perl -w
> 
> use warnings;
> use strict;
> 
> my $DEBUG=($0=~/1$/) ? '1' : '';
> use RW::Sql$DEBUG;
> use RW::Docs$DEBUG;
> 
> I've found that you can use "require" and pass a path.  I understand that 
> require is run time, while use is compile time.  Are there any down-sides to 
> using require?
> 
> -- 
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
> 
> 

Jim Gibson

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




Re: regex help - only one value returned

2020-12-02 Thread Jim Gibson
In your original example:

print "match1='$1' '$2'\n" if ($T=~/^((mr|mrs|miss|dr|prof|sir) .{5,}?)\n/smi);
print "match2='$1' '$2'\n" if ($T=~/^(mr|mrs|miss|dr|prof|sir .{5,}?)\n/smi);

the interior parentheses in example one terminates the alternation, so the last 
string is ’sir’.

In example two, the alternation is not terminated until the first ‘)', so the 
last string is ’sir .{5,}?’. followed in the regular expression by the “\n” 
character. Since in $T ‘miss’ is not followed by an \n, the match fails. Vlado 
has explained how to group and terminate the alternation without capturing the 
match result.


> On Dec 2, 2020, at 6:08 AM, Gary Stainburn  
> wrote:
> 
> On 02/12/2020 13:56, Vlado Keselj wrote:
>> Well, it seems that the first one is what you want, but you just need to
>> use $1 and ignore $2.
>> 
>> You do need parentheses in '(mr|mrs|miss|dr|prof|sir)' but if you do not
>> want for them to be captured in $2, you can use:
>> '(?:mr|mrs|miss|dr|prof|sir)'.  For example:
>> 
>> print "match3='$1' '$2'\n" if
>> ($T=~/^((?:mr|mrs|miss|dr|prof|sir) .{5,}?)\n/smi);
>> 
>> would give output:
>> 
>> match3='Miss Jayne Doe' ''
> Perfect, thank you.
> 
> I can't ignore $2 as it's in a loop with other regex that genuinely returns 
> multiple matches.  The amendment to the REGEX worked perfectly.

It is always best to save the results of a match with capturing in another 
variable. The capturing variables $1, $2, etc. are not reassigned if a match 
fails, so if you use them after a failed match, they will be the values left 
over from a previous match. So do this:

my $salutation = $1;
my $name = $2;

If you don’t want a possible undefined value, so this instead:

my $name = $2 || '';


Jim Gibson
j...@gibson.org

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




Re: Varnish module configuration

2020-11-15 Thread Jim Gibson


> On Nov 15, 2020, at 2:42 AM, Marco Shaw  wrote:
> 
> https://metacpan.org/source/RCL/Varnish-CLI-0.03/lib%2FVarnish%2FCLI.pm
> 
> I don't know if I'm doing something wrong.  I'm trying to use this CLI 
> against an upgraded Varnish server and it seems the new version is built with 
> a secret being required to connect remotely.
> 
> I think the relevant sections are below.
> 
> For #1, I couldn't find any examples online, but my guess is I can just 
> modify my like this:
> my $varnish = Varnish::CLI->new( secret => 'ENTER_LONG_STRING_HERE' ); 
> 
> It asks for the contents of my secret (/etc/varnish/secret) file which is 
> GUID-like and I entered that directly in the line above.  I tried with both 
> single quotes and none.

Try reading the contents of the /etc/varnish/secret file into a variable and 
pass that to the new() method:

my $secret;
{
local $/;
open my $fh, '<', ‘/etc/varnish/secret or die "can't open secret 
file: $!";
$secret = <$fh>;
}

> 
> If I have #1 right, I think I've confirmed a "107" is being returned with a 
> telnet session, but it doesn't appear that #2 is working right as this comes 
> directly on the screen:
> "Connection failed: authentication required, but no secret given\n" 
> 
> I don't understand this syntax:
> if( not $self->secret() ){ 

$self appears to be an object, normally a pointer to a hash.
$self->secret() executes a call to the object method secret() and returns a 
value, which is probably the secret key.
( not $self->secret() ) is a logical expression negating the value returned by 
the secret() method.

Therefore, as you have correctly surmised, the expression will evaluate to true 
if $self has no secret value. 

> 
> My guess is it evaluates if my secret variable is empty?
> 

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




Re: perl script with wrong

2019-10-13 Thread Jim Gibson



> On Oct 10, 2019, at 6:04 PM, 刘东  wrote:
> 
> Dear friends,
> I have written a perl script to get seprated files, but finally I every file 
> included multiple files appeared before,
> for example, 1 file 2M, 2 file 5 M( included last one), 3 file 6 M (included 
> last two ones), ...
> but I expected as 1 file 2M, 2 file 3M, 3 file 1 M, …

You are adding data to %hash for each file read. Since %hash is global, it will 
contain all of the data from the current file and all previously read files.

If you want to start with an empty hash for each file, then declare %hash 
inside of the foreach loop or assign %hash to () at the beginning of the 
foreach loop.

> the script as follows:
> #! /usr/bin/perl
> 
> use strict;
> use warnings;
> use Getopt::Long;
> 
> my ($dir, $files, $file_dir, $file_name, $file_main, $file_format, $outfile);
> my %hash;
> 
> GetOptions ('dr=s'  =>\$dir);
> 
> foreach $files (glob("$dir/*.txt")) {
>   ($file_dir, $file_main) = split (/\/\//,$files);
>   ($file_name,$file_format) =split(/\./,$file_main);
>   $outfile= $file_name."_sg.txt";
>   
> open OUT,">",$outfile or die "can't open $outfile";
> open IN,"<$files" or die "can't read open $files";
> 
> while(defined (my $line= )){
> chomp($line);
> $line =~s/^\s+//g;
> next if ($line =~ m/^S*$/);
> my ($id,$start,$end)= (split /\t/,$line)[0,1,2]; # no 3 after "split 
> /\t/,$line"
> my $m_lenth = $end-$start+1; 
> 
> if (exists $hash{$id}) { 
> my ($start,$end)= (split /\t/,$hash{$id})[1,2]; 
> if ($m_lenth > ($end-$start+1)) { 
> $hash{$id} = $line;
> }
> } else { 
> $hash{$id} = $line; 
> }
>   }
>   
> my @val = values %hash;
> print OUT "@val\n"; 
> 
> close OUT;
> close IN;
> }
> 
> 
> 
> 
> 
> --
> Hunan Normal University, Changsha, China:Dong Liu
>  
> 格言:积土而为山,积水而为海;
> 知识在于积累,成功在于勤奋。
> 
> 
>  

Jim Gibson
j...@gibson.org

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




Re: Hi Folks : I'm trying to create a regular expression for finding a # wishing a dataset for only a number that is a multiple of 5

2019-09-08 Thread Jim Gibson



> On Sep 8, 2019, at 6:36 PM, Olivier  wrote:
> 
> Jim Gibson  writes:
> 
>> On Sep 8, 2019, at 3:39 PM, Mike  wrote:
>>> 
>>> 
>>> It's probably best if you write a short script
>>> that reads a __DATA__ section of data.
>>> Then tell us what it does and what you expected
>>> it to do.
>>> 
>>> Off hand I don't see anything wrong with your regex,
>>> but I don't know what you expect it to do.
>>> 
>> 
>> I expect it to return a positive value if $t contains a number anywhere 
>> within it and put that number in the $1 capture variable.
> 
> Well, that is not what is in your regex: you look for a decimal number
> ending with 0 or 5, and it must be the last number of the line.
> 
> What about something simple like:
> 
>/(\d*[05])\D*$/

I prefer the explicit (?:…|…) structure that tells the reader that an alternate 
expression is being used. Also, the “zero or more” * operator can be very slow 
for long strings.

> 
> The Regex Coach is your friend (and works well under wine).
> 
> It alsways help to present with some sample data.

If you want to use this regex, then you should test it yourself. I did.

> 
> Best regards,
> 
> Olivier
> 
>>> 
>>> Mike
>>> 
>>> 
>>> On 9/8/2019 4:34 PM, Jim Gibson wrote:
>>>> On Sep 8, 2019, at 1:30 PM, Gautam Desai  
>>>> wrote:
>>>>> Do you guys have any pointers ?
>>>>$t =~ m{
>>>>(   # capture matched number in $1
>>>>  \d*   # match zero or more decimal digits
>>>>  [05]  # followed by a '0' or '5'
>>>>)   # end of capture
>>>>(?: # followed by either:
>>>>  \D    # a non-digit
>>>>|   # or
>>>>  $ # the end of the string
>>>>)
>>>>    }x
>>>> 
>>> 
>>> -- 
>>> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
>>> For additional commands, e-mail: beginners-h...@perl.org
>>> http://learn.perl.org/
>>> 
>>> 
>> 
>> Jim Gibson
>> j...@gibson.org
> 
> -- 
> 
> -- 
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/

Jim Gibson
j...@gibson.org

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




Re: Hi Folks : I'm trying to create a regular expression for finding a # wishing a dataset for only a number that is a multiple of 5

2019-09-08 Thread Jim Gibson
On Sep 8, 2019, at 3:39 PM, Mike  wrote:
> 
> 
> It's probably best if you write a short script
> that reads a __DATA__ section of data.
> Then tell us what it does and what you expected
> it to do.
> 
> Off hand I don't see anything wrong with your regex,
> but I don't know what you expect it to do.
> 

I expect it to return a positive value if $t contains a number anywhere within 
it and put that number in the $1 capture variable.

> 
> Mike
> 
> 
> On 9/8/2019 4:34 PM, Jim Gibson wrote:
>> On Sep 8, 2019, at 1:30 PM, Gautam Desai  
>> wrote:
>>> Do you guys have any pointers ?
>>  $t =~ m{
>>  (   # capture matched number in $1
>>\d*   # match zero or more decimal digits
>>[05]  # followed by a '0' or '5'
>>  )   # end of capture
>>  (?: # followed by either:
>>\D# a non-digit
>>  |   # or
>>$ # the end of the string
>>  )
>>  }x
>> 
> 
> -- 
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
> 
> 

Jim Gibson
j...@gibson.org

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




Re: Hi Folks : I'm trying to create a regular expression for finding a # wishing a dataset for only a number that is a multiple of 5

2019-09-08 Thread Jim Gibson
On Sep 8, 2019, at 1:30 PM, Gautam Desai  wrote:
> 
> Do you guys have any pointers ? 

$t =~ m{ 
(   # capture matched number in $1
  \d*   # match zero or more decimal digits
  [05]  # followed by a '0' or '5'
)   # end of capture
(?: # followed by either:
  \D# a non-digit
|   # or
  $ # the end of the string 
) 
}x 

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




Re: reading text data to variable

2018-12-28 Thread Jim Gibson
If you want to process lines in a file twice, there are two simple choices:

1. Save the lines in a array the first time you read the file, then traverse 
the array as many times as you want. This works unless you have a humungous 
file.

2. Call seek(,0,0) on the file handle and read the file again.

> On Dec 26, 2018, at 9:40 AM, Eldon DeHart  wrote:
> 
> I can't figure out how to read each line of text back into my program and 
> assign it to the variable again.
> Thanks for help in advance.
> Eldon
> -- 
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/

Jim Gibson
jimsgib...@gmail.com

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




Re: Syntax "||" before sub

2018-11-24 Thread Jim Gibson



> On Nov 24, 2018, at 12:49 PM, David Precious  wrote:
> 
>  I went to perldoc perlop expecting to be able to find a
> section to point the OP at as a "here's the documentation for it", and
> couldn't find anything particularly useful.

I was able to find this in “perldoc perlop”:

 Assignment Operators

"=" is the ordinary assignment operator.

Assignment operators work as in C. That is,

$x += 2;

is equivalent to

$x = $x + 2;

although without duplicating any side effects that dereferencing the
lvalue might trigger, such as from "tie()". Other assignment operators
work similarly. The following are recognized:

**=+=*=&=&.=<<=&&=
 -=/=  |=|.=>>=||=
 .=%=^=^.= //=
 x=

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




Re: Code Assistance Pls

2018-11-21 Thread Jim Gibson



> On Nov 21, 2018, at 3:08 AM, Amanda Paziuk  wrote:
> 
> Folks,
> 
> I'm hoping someone can assist as I'm having difficulty with parsing a section 
> of the following configuration:
> 
> This is the code I have:
> 
> open (IN, $file); # only sharing this because you need to know where 
> @list is derived.

using the three argument version of open with a lexically-scoped variable and 
adding error checking is preferred:

open( my $in, ‘<‘, $file ) or die(“Can’t open file $file: $!”); 

> while () {
> chomp;
> next unless /file-id/;
> my $datum = $_;
> $datum =~ s/(^\s+|\s+$)//g;
> $datum =~ s/file-id //g;
> push @list, $datum; # should only contain '1', and '3'
> }

That loop can be simplified:

while( my $line = <$in> ) {
if( $line =~ /^\s*file-id\s*(\d+)/ ) {
push( @list, $1 );
}
}

> close IN;
> 
> # ideally this would take a snippet of that config
> $count = 0;
> foreach my $i (@list){ # loops through dynamically-learned file IDs
> open (IN, $file);
> while () {
> chomp;
> if (/^file-id $i/) {
> $count = 1;
> }
> elsif (/^exit/) { # this just keeps matching every exit 
> with that same indent
> $count = 0;
> }
> elsif ($count) {
> if (/text/) {
> push @logfiles, $_; # successfully captures only what I 
> want in the array
> }
> }
> }
> close IN;
> }
> 
> The first is to find all file-id lines then isolate for the number; the 
> second loop is to take a snip:
> 
> file-id 1 
> text
> exit
> 
> What it winds up doing is:
> 
> file-id 1 
> text
> exit
> file-id 3
> text
> exit
> exit
> exit
> exit
> exit
> exit 
> … 

Is that what ends up in the @logfiles array? I don’t see how that can be. You 
are testing to see if text lines contain the string ’text’ before adding the 
line to the @logfiles array, and lines which only contain ‘exit’ do not contain 
’text'. Please show us your actual code.

> 
> This is the nightmare config structure that I need to deal with throughout 
> the file...lots of "exits" so it matches an awful lot...
> 
> log 
> file-id 1 
> text
> exit 
> file-id 3
> text
> exit
> exit 
> 
> The configuration is thousands of lines long, indented like that with exit at 
> various levels, so this is just one part of what I'm trying to analyze. What 
> it's doing is making the server work harder with all the extra stuff it's 
> catching and leaves me wide-open for false positives...
> 
> My question: does anyone have a better way to take those snippets, stopping 
> after the first match of "exit"? (Please don't flame, I'm asking for help.)
> 
> Amanda

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




Re: use Time::Piece

2018-10-31 Thread Jim Gibson
On Oct 31, 2018, at 1:29 PM, Martin McCormick  wrote:
> 
> 
> I'd like to say that it's working but not yet.  There seems to be
> nothing wrong with the string now.
> 
> my $t1 = Time::Piece->strptime("$obtime[1], %d %b %Y %H:%M:%S %z”);

strptime is a method with two arguments:  string to be parsed, format to be 
used for parsing. You have one argument: a double-quoted string.

my $t1 = Time::Piece->strptime($obtime[1], "%d %b %Y %H:%M:%S %z”);

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




Re: How to compare timestamp in two different files(regex)

2018-10-25 Thread Jim Gibson
(Please reply to the list.)

If you have written code that extracts the date and time from the ‘LOG flle 
opened’ lines in the log file, then please show us your code. You seem to be 
asking other people to write your program for you. You will get better help if 
you appear to be making an effort to solve these problems yourself.

Anyone wishing to get help from a forum such as beginners@perl.org would do 
well to read this website on how to ask smart questions:

<http://www.catb.org/~esr/faqs/smart-questions.html>

Now, to address your problem:

If you have a starting time and an ending time for a window within which you 
wish to print lines from a log file, you can use a flag variable to indicate 
when the lines you are reading are within that window. The pseudo-logic would 
be something like this:

1.initialize print flag to false
2. Save starting and ending times in variables
3. loop to read or process sequential lines in the file
  a. See if line contains time
  b. If it does, extract time
  c. Compare time in line to starting time
  d. If line time is greater than or equal to start time, set print flag to true
  e. If line time is greater than ending time, set print flag to false
  f. If print flag is true print line
  g. End of loop — process next line

If you need help with any of these steps, please show us your code, what your 
code is doing, and what you expect your code to do that it is not doing.

Thanks.
 
> On Oct 24, 2018, at 10:50 PM, Asad  wrote:
> 
> Hi Jim/All,
> 
>  I have already done that now the issue is how do I  print  the 
> lines from file2 only between start $t2 and <$t3  then process these lines is 
> next step ?
>  Please share the code if you have .
> 
> Thanks,
> 
> 
> On Thu, Oct 25, 2018 at 11:04 AM Jim Gibson  wrote:
> 
> 
> > On Oct 24, 2018, at 9:54 PM, Asad  wrote:
> > 
> > Thank all now I am able to progress :
> > 
> > file1  i am able to extract the start and end timestamp 
> > file 2  i am able to extract the timestamp 
> > 
> > used the following 
> > my $t1 = Time::Piece->strptime('Feb 23 01:10:28 2018', '%b %d %H:%M:%S 
> > %Y'); coming from file1
> > 
> > my $t2 = Time::Piece->strptime('02/23/18 01:10:33', '%m/%d/%y %H:%M:%S');   
> > coming from file2
> > 
> > my $t3 = Time::Piece->strptime('Feb 23 01:10:36 2018', '%b %d %H:%M:%S 
> > %Y');  coming from file 1
> > 
> > if ($t2 > $t1 and $t2 < $t3) { ... }   till here it working fine
> > 
> >  now I would like to print all lines from file2 starting from  t2 02/23/18 
> > 01:10:33 till very next timestamp which will be  greater than t3 :
> > 
> > 
> > 
> > for example the file2  would look like this:
> > 
> > ===
> > 
> >  LOG file opened at 02/23/18 01:10:33
> > 
> > ERR-05007:   Warning: Intra source concurrency disabled because the 
> > preprocessor option is being used.
> > 
> > Field Definitions for table OPATCH_XML_INV
> > 
> > eject rows with all null fields
> > 
> >   Fields in Data Source: 
> > 
> > 
> > 
> > ERR-04095:failed: Unable to create patchObject
> > 
> > Possible causes are:
> > 
> >  "
> > 
> >  LOG file opened at 04/26/18 06:10:33
> > 
> > ===
> >   
> > 
> > This logfile may have other time but i would to extract only the above 
> > lines because messages occured between t1 and t3 after I extract these i 
> > want to print the error lines for example ERR-05007
> > 
> > the issue I am facing if there are multiple error in the file it is 
> > printing for each occurance of  ERR-05007 instead it should print only the 
> > error lines between t1 and t3 from file2
> > 
> > Please advice ,
> > 
> > thanks,
> 
> For each line is the file, use a regular expression to look for lines 
> starting with ‘LOG file opened at’ and extract the time that follows in that 
> line. Then, use Time::Piece to create an object of that class using the 
> date/time extracted. Then, you can compare the time in that line to your 
> start and stop times in $t2 and $t3 (or is it $t1 and $t3?).
> 
> 
> Jim Gibson
> 
> -- 
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
> 
> 
> 
> 
> -- 
> Asad Hasan
> +91 9582111698

Jim Gibson

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




Re: How to compare timestamp in two different files(regex)

2018-10-24 Thread Jim Gibson



> On Oct 24, 2018, at 9:54 PM, Asad  wrote:
> 
> Thank all now I am able to progress :
> 
> file1  i am able to extract the start and end timestamp 
> file 2  i am able to extract the timestamp 
> 
> used the following 
> my $t1 = Time::Piece->strptime('Feb 23 01:10:28 2018', '%b %d %H:%M:%S %Y'); 
> coming from file1
> 
> my $t2 = Time::Piece->strptime('02/23/18 01:10:33', '%m/%d/%y %H:%M:%S'); 
>   coming from file2
> 
> my $t3 = Time::Piece->strptime('Feb 23 01:10:36 2018', '%b %d %H:%M:%S %Y');  
> coming from file 1
> 
> if ($t2 > $t1 and $t2 < $t3) { ... }   till here it working fine
> 
>  now I would like to print all lines from file2 starting from  t2 02/23/18 
> 01:10:33 till very next timestamp which will be  greater than t3 :
> 
> 
> 
> for example the file2  would look like this:
> 
> ===
> 
>  LOG file opened at 02/23/18 01:10:33
> 
> ERR-05007:   Warning: Intra source concurrency disabled because the 
> preprocessor option is being used.
> 
> Field Definitions for table OPATCH_XML_INV
> 
> eject rows with all null fields
> 
>   Fields in Data Source: 
> 
> 
> 
> ERR-04095:failed: Unable to create patchObject
> 
> Possible causes are:
> 
>  "
> 
>  LOG file opened at 04/26/18 06:10:33
> 
> ===
>   
> 
> This logfile may have other time but i would to extract only the above lines 
> because messages occured between t1 and t3 after I extract these i want to 
> print the error lines for example ERR-05007
> 
> the issue I am facing if there are multiple error in the file it is printing 
> for each occurance of  ERR-05007 instead it should print only the error lines 
> between t1 and t3 from file2
> 
> Please advice ,
> 
> thanks,

For each line is the file, use a regular expression to look for lines starting 
with ‘LOG file opened at’ and extract the time that follows in that line. Then, 
use Time::Piece to create an object of that class using the date/time 
extracted. Then, you can compare the time in that line to your start and stop 
times in $t2 and $t3 (or is it $t1 and $t3?).


Jim Gibson

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




Re: How to compare timestamp in two different files

2018-10-22 Thread Jim Gibson
On Oct 22, 2018, at 9:12 PM, Asad  wrote:
> 
> file1 :
> Patching tool version 12.1.0.2.0 Production on Fri Feb 23 01:10:28 2018
> 
> Bootstrapping registry and package to current versions...done
> statement ERR-2001: table is corrupt check for cause 
> 
> could not determine the current status.
> 
> file2 :
> 
>  LOG file opened at 02/03/18 01:11:05
> 
> DUP-05004:   statement1
> DUP-05007:   statement2
> 
>  
>  LOG file opened at 02/03/18 01:11:14
> 
> DUP-05004:   statement1
> 
> DUP-05007:   statement2
> 
> 
>  LOG file opened at 02/23/18 01:10:33
> 
> DUP-05004:   statement1
> 
> DUP-05007:   statement2
> 
> I need to look for the ERR-2001 in file1 if it matches then go to file2 and 
> print the message nearest to the timestamp found in file1 within two minutes 
> of range .
> 
> so in this case file1 :  Fri Feb 23 01:10:28 2018
>range   file1 +2 mins :02/23/18 01:12:28
> check in file 2 nearest to file1 and within range : 02/23/18 01:10:33 
> 
> how do i compare two timestamps in different format and within range  ?

You would first convert the two timestamps to a common format, preferably one 
that used a numerical value to express times. I know of two such: the Unix 
epoch time that uses an integer to represent the number of seconds since 1 Jan 
1970 UTM and the Julian date that uses a floating-point number to represent the 
number of days since 1 Jan 4713 BCE.

Are you looking for a Perl solution or a Python one?

For Perl, you should investigate time and date modules available on CPAN, such 
as Date::Manip or Date::Calc.

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




Re: sftp code to use

2018-10-21 Thread Jim Gibson
Have you looked at the Net::SFTP module?

<https://metacpan.org/pod/Net::SFTP>


> On Oct 21, 2018, at 10:56 AM, Asad  wrote:
> 
> Hi All ,
> 
>   I need to accomplish the following task . i was trying in python using 
> subprocess and adive how to proceed will be helpful 
> 
> 
> sftp u...@xyx.com 1212
> pasword:xxx
> cd /patch1
> get patch1.zip
> unzip patch1.zip
> sqlplus / as sysdba ===> connect to oracle database 
> sql>startup
> 
> 
> Thanks,
> 
> -- 
> Asad Hasan
> +91 9582111698

Jim Gibson

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




Re: Regex for date

2018-08-25 Thread Jim Gibson
Many Perl modules have been written to parse and manipulate dates and times. 
Some come with Perl; others are available at www.cpan.org.

Check out the Date::Manip, Date::Parse, or DateTime modules.

> On Aug 25, 2018, at 4:06 AM, Asad  wrote:
> 
> Hi All ,
> 
> I need  a regex to match the date : Sat Aug 25 08:41:03 2018 and 
> covert into a format : '%m/%d/%Y %H:%M:%S' 
> 
> Thanks, 
> 
> -- 
> Asad Hasan
> +91 9582111698



Jim Gibson

--
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 stat script

2018-07-12 Thread Jim Gibson


> On Jul 12, 2018, at 5:50 AM, Lauren C.  wrote:
> 
> thanks for the kind helps.
> do you know what the expression in { } stands for?
> 
> ^(\S+) - - \[(\S+).*\] \"GET (.*?/)\s+

Here is a breakdown:

^   Start looking for matches at beginning of string
(\S+)   Match a consecutive sequence of non-whitespace characters and save in 
the $1 variable
—   Match the literal string ‘ — ‘
\[  Match the character ‘[‘
(\S+)   Match a consecutive sequence of non-whitespace characters and save in 
the $2 variable
.*  Match any consecutive zero or more characters
\]  Match the character ‘]’
(space) Match a space character
\”  Match the character ‘“‘
GET Match the literal string ‘GET ‘ (with a space at the end)
(.*?/)  Match the shortest string of any consecutive characters up to but not 
including a following whitespace and save in $3
\s+ Match any consecutive sequence of whitespace characters

If all of the above entities are matched, then the regular expression 
evaluation returns true and the 41, $2, and $3 variables are assigned to their 
captured matches.

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




Re: Questions about CGI

2018-06-06 Thread Jim Gibson



> On Jun 6, 2018, at 2:16 PM, Ahmad Bilal  wrote:
> 
> Ok, I went over to previously answered questions under the cgi tag here on 
> stackoverflow.

This message was posted to the Perl Beginners list, so you are not at 
Stackoverflow any more.
> 
> This seems to be the most voted one: What is Common Gateway Interface (CGI)?
> 
> But it still doesn't clear a few things, which I'm asking here.
> 
> Since RFC3875 is only a informational doc, and there is no finalized standard.
> 
>   • Who implements CGI protocol? Who defines its "standard behavior" on 
> servers such as Apache.

The CGI protocol is implemented by web servers and web browsers. It is a way 
for browsers to query a server and get dynamic information, rather than a 
static web page. The CGI request is part of the Hypertext Transfer Protocol 
(HTTP). It allows parameters to be sent by the browser to the server, which 
then uses the values of these parameters to generate a dynamic web page that it 
sends back to the browser.

> 
>   • How does C files work with CGI in modern environment. Please 
> elaborate using a "Hello World!" as a response to a form submission.

You can write a CGI program in just about any language. Since this is a Perl 
list, maybe you should be asking about CGI programming in Perl. I have written 
CGI programs in Perl, but now use PHP (for compatibility with existing CGI 
scripts).

Perl has modules to assist in CGI program development. The oldest of these is 
the CGI.pm module, but it has now fallen out of favor, and other modules are 
now recommended. I haven’t used any (or done any CGI programming in Perl for a 
long time), so I can’t recommend any from personal experience.

Check out these pages:

<https://metacpan.org/pod/CGI>
<https://metacpan.org/pod/Task::Kensho#Task::Kensho::WebDev:-Web-Development>


> 
> 
> 
> -- 
> Ahmad Bilal
> 



Jim Gibson

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




Re: How to use Text::Wrap correctly

2017-08-19 Thread Jim Gibson

> On Aug 18, 2017, at 6:05 AM, Harry Putnam <rea...@newsguy.com> wrote:
> 
> jimsgib...@gmail.com (Jim Gibson) writes:
>>> 
> 
> A second attempt trying to use your last example as inspiration
> follows:
> 
> ---8< snip -8< snip   --
> 
> use strict;
> use warnings;
> use Text::Wrap;
> 
> my $rgx = qr/@{[shift]}/;
> 
> $Text::Wrap::columns = 68;
> 
> 
> while ( my $line = <> ) {
>  if (/$rgx/) {
>  print "\n";
>  print wrap(",", $line);
>  }
> }
> 
> ---8< snip -8< snip   --
> 
> Output from same `logs' file:
> 
> Use of uninitialized value $_ in pattern match (m//) at 
> /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 1.
> Use of uninitialized value $_ in pattern match (m//) at 
> /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 2.
> Use of uninitialized value $_ in pattern match (m//) at 
> /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 3.
> Use of uninitialized value $_ in pattern match (m//) at 
> /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 4.
> Use of uninitialized value $_ in pattern match (m//) at 
> /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 5.
> Use of uninitialized value $_ in pattern match (m//) at 
> /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 6.
> Use of uninitialized value $_ in pattern match (m//) at 
> /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 7.
> Use of uninitialized value $_ in pattern match (m//) at 
> /vcs/d0/home/reader/scripts/perl/logwrp line 48, <> line 8.

There is an error in what I posted (sorry). The input is read into the $line 
variable, but your regular expression is implicitly testing the default 
variable $_. The loop should be:


while ( my $line = <> ) {
  if ( $line =~ /$rgx/ ) {
 print "\n";
 print wrap(",", $line);
  }
}

I don’t know what Text::Wrap is complaining about. It helps if you are able to 
include a text string in your posted source code that demonstrates the problem. 
Use the built-in DATA file handle to include data within your program source. 
Check out ‘perldoc perldata’ and search for “__DATA__”. This is the pattern:

...
while ( my $line =  ) {
  if ( $line =~ /$rgx/ ) {
 print "\n";
 print wrap(",", $line);
  }
}
...
__DATA__
This is data to be read using the  operation.


Jim Gibson
jgib...@snowlands.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 use Text::Wrap correctly

2017-08-13 Thread Jim Gibson

> On Aug 13, 2017, at 6:02 PM, Harry Putnam <rea...@newsguy.com> wrote:
> 
> My aim:
> 
> Run certain kinds of log file lines thru a perl script that will:
> 
> 1) Identify each line by regex that finds pattern at start of line
> 2) When such a line is found, print newline first then
> 3) wrap any lines longer than specified number of columns.
> 
> 
> I was not able to divine from `perldoc Text::Wrap' how to really use
> it to do what I want.
> 
> my non-working effort stripped to the bare bones:
> 
> use strict;
> use warnings;
> use Text::Wrap;
> 
> my $rgx = qr/@{[shift]}/;
> 
> $Text::Wrap::columns = 68;
> 
> my @text;
> 
> while (<>) {
> if (/$rgx/) {
>   print "\n";
>   print wrap(",", @text);
> }
> }
> 
> It wasn't at all clear from perldoc Text::Wrap how @text is supposed
> to be populated.

@text is a list of scalar strings passed to the wrap subroutine. You can pass a 
single string also. Try this loop instead:

while (<>) {
if (/$rgx/) {
  print "\n";
  print wrap(",", $_);
}
}

It is usually better to use explicit variables:

while ( my $line = <> ) {
if (/$rgx/) {
  print "\n";
  print wrap(",", $line);
}
}




Jim Gibson

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




Re: Filehandle within foreach loop

2017-07-12 Thread Jim Gibson
If you wish to terminate execution of a foreach loop without iterating over all 
of the elements (@files, in this case) use the “last” statement:

foreach my $file ( @files ) {
 # process file
 open( my $fh, ‘<‘, $file ) or die(…);
 while( my $line = <$fh> ) {
   # process line
 }
 close ($fh) or die( … );

 last if (some_condition);
}

If you wish to terminate the foreach loop from inside the while loop, you can 
give the foreach loop a label and use the label in the “last” statement. 
Without an explicit label, “last” will terminate the innermost loop (the while 
loop here):

ALL: foreach my $file ( @files ) {
 # process file
 open( my $fh, ‘<‘, $file ) or die(…);
 while( my $line = <$fh> ) {
   # process line
   last ALL if (some_condition);
 }
 close ($fh) or die( … );
}

However, in that case you have skipped the close statement, and the close will 
happen automatically when the file handle $fh goes out of scope, but you cannot 
do any explicit error checking on the close.


> On Jul 12, 2017, at 12:20 PM, perl kamal <kamal.p...@gmail.com> wrote:
> 
> Hello All,
> 
> I would like to read multiple files and process them.But we could read the 
> first file alone and the rest are skipped from the while loop. Please correct 
> me where am i missing the logic.Thanks. 
> 
> use strict;
> use warnings;
> my @files=qw(Alpha.txt Beta.txt Gama.txt);
> 
> foreach my $file (@files)
> {
> open (my $FH, $file) or die "could not open file\n";
> 
> while( my $line = <$FH> ){
> #[process the lines & hash construction.]
> }
> close $FH;
> }
> 
> Regards,
> Kamal.



Jim Gibson

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




Re: File::Find .. still confused slightly

2017-07-05 Thread Jim Gibson
You have a logic error in your code somewhere. Your logic for counting the 
files with a name matching a certain pattern is too complicated to follow and 
point out where your error lies and how to fix it. The basic problem is that 
your logic depends upon detecting when the directory name changes, and will 
therefore not work on the last file encountered. It also depends upon all of 
the files in a directory being scanned sequentially. While that seems to work, 
it is not guaranteed by File::Find.

A simpler method for counting files in each directory would be to use a hash 
with the directory name as key and the number of files as value. Here is a 
program for doing that:

#!/usr/bin/env perl
use strict;
use warnings;
use File::Find;

my $startdir = './dir1';
my %counts;

find sub {
return unless -f;
return unless /^\d+$/;
$counts{$File::Find::dir}++;
}, $startdir;

my( $total_dir, $total_files);
print "# Files   Directory\n---   ---\n";
for my $dir ( sort keys %counts ) {
(my $shortdir = $dir) =~ s{.*News/agent/nntp}{};
my $nfiles = $counts{$dir};
printf "%5d %s\n", $nfiles, $shortdir;
$total_dir++;
$total_files += $nfiles;
}
print "\n<$total_files> files in <$total_dir> directories\n”;


Note that I recommend keeping the raw numerical data (file counts) and not 
saving the output lines. Generate the output lines when you print them.


Jim Gibson

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




Re: File::Find report file count per directory

2017-06-28 Thread Jim Gibson
On Jun 28, 2017, at 2:10 PM, Harry Putnam <rea...@newsguy.com> wrote:
> 
> 1) I want to count numeric named files in each directory.
> 
> 2) I want to capture the name of the directory those files are in
> 
> 3) I want to print the directory name and the count (if any) for each
>  directory.
> 
> I know that all the information I want to extract is available in
> File::Find.
> 
> Just having trouble seeing how to get at it when I want it.
> 
> Connecting the directory name with the file count is the rub for me.
> 
> I googled extensively but have not found this specific usage.  I get
> piles of examples for just counting files throughout a hierarchy.
> But not giving a count and directory name of `each' directory.
> 
> I've done several hours of fumbling around and have produced several
> abject failures.
> 
> Finally got something that did what I wanted.
> 
> The script below does those three things... But I have a sneaking
> feeling there is some easier way to extract the info.  Something
> simpler that is right in front of me... but escaping me.
> 
> The test directory structure looks like this:
> 
> ls -R dir1
> dir1:
> 111  222  333  dir2
> 
> dir1/dir2:
> 111  222  333  dir3
> 
> dir1/dir2/dir3:
> 111  222  333
> 
> ff1c:
> ---   ---   ---=---   ---   ---
> 
> my $usage =
> "Purpose: bleh
> Usage: bleh
> ";
> 
> my $dir;
> if (! @ARGV){
>  warn "$usage",
>   "Usage tripped: line: <" . __LINE__ . ">\n",
>   "We need at least 1 top directory\n";
>  exit;
> } elsif (@ARGV > 1) {
>  warn "$usage",
>   "Usage tripped: line: <" . __LINE__ . ">\n",
>   "Too many cmdline arguments\n";
> }
> 
> $dir = shift;
> if (! -d $dir) {
>  warn "$usage",
>   "Usage tripped: line: <" . __LINE__ . ">\n",
>   "<$dir> not found .. aborting ..\n";
>  exit;
> }
> ---   ---   ---=---   ---   ---
> 
> ff1c out:
> 
>> ./ff1c
> 
> ./dir13
> ./dir1/dir2   3
> ./dir1/dir2/dir3  3
> (9) numeric files overall

I don’t see how the code you have posted can possibly produce the output you 
have reported. The code above looks like error checking that the user of the 
program has entered one argument, and that argument is the name of a directory.

How about posting the rest of your program. The error checking part is the 
least interesting part, as it is very straightforward and although it is a 
valuable part of any good program, it is not relevant to the discussion of how 
to count numerically-named files. So how about posting a program that includes 
only the part of Perl that you want people to evaluate.

If I had to do this, I would create a hash that had the directory name as a key 
and the number of files in that directory that have a numerical file name. I 
would use File::Find to traverse the directory tree, check the name of each 
non-directory file, and increment the count for the enclosing directory for 
each such file I found.

A line something like this:

$filecount{$File::Find::dir}++;

would be central to my program.




Jim Gibson

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




Re: keyboard input without pressing return?

2017-05-14 Thread Jim Gibson

> On May 5, 2017, at 6:06 PM, lee <l...@yagibdah.de> wrote:
> 
> 
> Hi,
> 
> how can a sleeping program react to a key that was pressed without
> return being pressed?
> 

See ‘perldoc -q "How can I read a single character from a file? From the 
keyboard?”


Jim Gibson
jgib...@snowlands.org

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




Re: prime factors

2017-05-02 Thread Jim Gibson

> On May 2, 2017, at 7:58 AM, derrick cope <derr...@thecopes.me> wrote:
> 
> I was writing a program to solve the #3 exercise on project Euler. I needed 
> to find the prime factors of a given number.
> I have solved it already but a couple of the ways I tried to solve the 
> problem caused a problem.

Exercise #3 is to find the largest prime factor of the number 600,851,475,143.

> 
> The below worked for smaller numbers but when I used the 12 digit number 
> given by project Euler I got "Out of memory!"
> 
> chomp( my $factor = <>);
> my @primefactor = grep { ( $_ ) } ( grep { $factor % $_ == 0 } 
> 1..$factor );

Presumably, you have entered the number 600851475143 into the command line that 
executes your program. Therefore, $factor is equal to 600851475143  and the 
expression 1..$factor will be a list of 600851475143 elements; ( 1, 2, 3, … , 
600851475143 ). You will need a computer with several petabytes of memory to 
store that list.

> 
> sub isprime { 
> my $numb = shift;
> my @quot = grep { 
>if ( $numb % $_ == 0 ) {1;
>} else { 0;} 
> } 2..$numb-1;
> unless ( @quot ) {
>1;
>#say "prime";
>} else {
>0;
>#say "not prime";
>}
> }

This function also generates a very long list of integers (2..$numb-1).

> 
> 
> This one worked but caused my computer to crash.
> 
> my $xxx = 1;
> while ( $xxx < $factor ) {
>if ( $factor % $xxx == 0 and ($xxx) ) {
>say $xxx;
>}
>$xxx++
> }
> 
> what is causing perl to do this?  Would using a module save memory?
> Thanks for any help.

Using a module would not save significant memory. You need to devise an 
algorithm that does not require long lists of numbers. You need to test each 
potential prime factor one at a time. You will also need to address the fact 
that Perl’s integers cannot represent the number 600851475143 in their normal 
32- or 64-bit formats. See ‘perldoc bignum’.

Also note that the smallest factor of any number cannot be larger than the 
square root of that number, so the function isprime need not consider potential 
factors larger than the square root of its argument.




Jim Gibson

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




Re: Warnings when sorting by hashref

2017-04-11 Thread Jim Gibson

> On Apr 11, 2017, at 6:13 AM, Mike Martin <m...@redtux.org.uk> wrote:
> 
> Hi
> 
> I have the following code as an example against a hash of hashes, to sort by 
> hashrf key
> 
> foreach my $opt (sort {uc($options{$b}->{type}) cmp uc($options{$a}->{type})} 
> keys %options){
>my $type=$options{$opt}->{vtype};
>$video_type->append_text($type) if defined($type) ;
>}
> 
> The sort function works perfectly, however perl throws up the following 
> warning for each line
> 
> Use of uninitialized value in uc at
> 
> Any ideas how to get rid of the warning

Make sure that all $options{$key}->{type} values are defined:

foreach my $key ( keys %options ) {
 $options{$key}->{type} = ‘’ unless defined $options{$key}->{type};
}

Substitute something else for ‘’ depending upon where you want to sort 
undefined {type} values in your sort order.


Jim Gibson

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




Re: Changing date format using carpout

2017-03-25 Thread Jim Gibson

> On Mar 25, 2017, at 8:51 AM, SSC_perl  wrote:
> 
>   I’ll sometimes use the following code at the beginning of a script to 
> log errors while testing:
> 
> BEGIN {
>   use CGI::Carp qw(carpout);
>   open(_STDERR,'>'); close STDERR;
>   open (my $log, '>>', 'logs/error.log') or warn("Couldn't open 
> error.log: $! \n");
>   carpout($log);
>   close ($log);
> }
> 
>   However, I would like to change the date format.  I’m not wild about 
> seeing the the full timestamp on every line:
> 
> [Sat Mar 25 08:05:58 2017]
> 
>   Is there a way I can format that to my liking?  I see there's a 
> ‘noTimestamp’ option to stop it from printing altogether, but I don’t see a 
> way to change the output.

The timestamp is generated in the stamp() function, which starts on line 387 of 
the source file Carp.pm. You can copy the source of the modules and edit the 
stamp function to generate a shorter timestamp. You could also try overriding 
the supplied function of the imported module with your own version (not sure 
exactly how that is done).

> 
>   Side question: is there a better way to accomplish what I’m doing 
> above?  I’m happy with what I already have (except for the date) but only 
> because I don’t know anything else.  I’d like to hear how others do this.

I usually write my own log files using normal file output functions. However, 
that is harder, but not impossible, when you are writing CGI programs.

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




Re: newbie question for parsing incoming mails

2017-02-16 Thread Jim Gibson

> On Feb 15, 2017, at 9:56 PM, Eko Budiharto  wrote:
> 
> Jim,
> I have one a couple more questions.
> -. For the header, what if, I just need the subject, the from, and the 
> recipient, what is the command? I read the manual in the 
> https://metacpan.org/pod/Email::MIME#header, it does not tell me how to 
> extract all of those.
> -. And then, for the email contents of the body, it just shows Content-Type: 
> multipart/alternative; boundary=f403045de9521d20cc054874ce1a 
> instead of the contents of the email body. How to extract it into string 
> because it is under html format.

Please post all questions to the list. There are other people who can answer 
your questions better than I can.

I just parse the text of the email using regular expressions, line by line:

my @lines = split(/[\n\r]+/,$text);

for( my $i = 0; $i <= $#lines; $i++ ) {
my $line = $lines[$i];
print "$i. $line\n" if $xdebug;

if( $line =~ m{ \A Subject:\ (.*) \z }x ) {
$subject = $1;

etc.

You can also try to use the Email::MIME::header method:

my $from = $mime->header(‘From’):

I haven’t used that, but it might be worth trying. Email::MIME is an extension 
of the Email::Simple class, so you can look at the documentation for that 
module as well. 
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: newbie question for parsing incoming mails

2017-02-15 Thread Jim Gibson
On Feb 15, 2017, at 7:10 PM, Eko Budiharto  wrote:
> 
> Jim, 
> if I want to extract all incoming emails from my qmail emails, how can 
> specify the folder location and specify the file name since the file name 
> always different?
> 
> Thx.

Use File::Find or opendir and readdir to find all of the emails in a directory 
tree. You need to figure out the parent directory, if there is one, of the 
local storage for your email client.

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




Re: newbie question for parsing incoming mails

2017-02-15 Thread Jim Gibson

> On Feb 15, 2017, at 8:10 PM, Eko Budiharto  wrote:
> 
> dear Jim,
> I tried to add lines to read file like this:
> 
> use Email::MIME;
> 
> my $file = '/var/qmail/mailnames/ name>/support/Maildir/cur/1487041394.M984019P23084V0803I00E03878.ABCD.NET,S=3987:2,';
> open my $ifh, '<', $file
>   or die "Cannot open '$file' for reading: $!";
> local $/ = '';
> my $contents = <$ifh>;
> close( $ifh );
> 
> my $mime = Email::MIME->($contents);  —> line 13
> 
> my @parts = $mime->parts();
> 
> for my $npart ( 0..$#parts ) {
>   my $part = $parts[$npart];
>   my $header = $part->header_obj();
>   my $htext = $header->as_string();
>   my $body = $part->body();
> 
>   print $header;
> }
> 
> after I ran its from CLI, I got an error message Undefined subroutine 
> ::MIME called at line 13.
> 
> what does the error mean?

That means I mistyped the line. It should be this:

my $mime = Email::MIME->new($contents);

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




Re: newbie question for parsing incoming mails

2017-02-15 Thread Jim Gibson

> On Feb 14, 2017, at 10:38 PM, Eko Budiharto <eko.budiha...@gmail.com> wrote:
> 
> dear all,
> I have a question. 
> If I would like to parse all incoming mails from my qmail, which perl module 
> is easy to use?
> my qmail emails incoming is /var/qmail/mailnames//support. In 
> this folder I already have preline in .qmail for piping emails to my perl 
> script.
> And, my perl script what I already have is like this:
>  
> #!/usr/bin/perl -w
>  
> use Mail::Internet;
> 
> my $mail = Mail::Internet->new( [  ] );
> my $headers = $mail->head->header_hashref;
> my @subject = @{${$headers}{'Subject'}}; # or otherwsie do it in list context 
> it works
> 
> print @subject;
> 
> 
> when I run it, I do not get anything.
> 
> please help.

I use Email::MIME to parse email messages. After reading the email file into 
the variable $text I do this:

my $mime = Email::MIME->($text);
my @parts = $mime->parts();

for my $npart ( 0..$#parts ) {
  my $part = $parts[$npart];
  my $header = $part->header_obj();
  my $htext = $header->as_string();
  my $body = $part->body();
  …
}





Jim Gibson

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




Re: warnings in Math::Complex

2017-02-09 Thread Jim Gibson

> On Feb 9, 2017, at 7:39 AM, Simon Bauer  wrote:
> 
> Hi,
>  
> when I turn on -W in one of my perl scripts then I get a lot of warnings 
> concerning Math::Complex
>  
>  Prototype mismatch: sub Math::Complex::abs (_) vs none at 
> /usr/share/perl/5.22/Math/Complex.pm line 667.
>  Prototype mismatch: sub Math::Complex::sqrt (_) vs none at 
> /usr/share/perl/5.22/Math/Complex.pm line 718.
>  Prototype mismatch: sub Math::Complex::exp (_) vs none at 
> /usr/share/perl/5.22/Math/Complex.pm line 849.
>  Prototype mismatch: sub Math::Complex::log (_) vs none at 
> /usr/share/perl/5.22/Math/Complex.pm line 888.
>  Prototype mismatch: sub Math::Complex::cos (_) vs none at 
> /usr/share/perl/5.22/Math/Complex.pm line 935.
>  Prototype mismatch: sub Math::Complex::sin (_) vs none at 
> /usr/share/perl/5.22/Math/Complex.pm line 952.

Put the following in your Perl program to turn on warnings in the enclosing 
block only (i.e., just your program and not external modules):

  use warnings;

See the following for more information:

perldoc warnings
perldoc perllexwarn

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




Re: perl for machine learning

2017-02-07 Thread Jim Gibson

> On Feb 7, 2017, at 5:47 PM, community tech <commun...@dnsbed.com> wrote:
> 
> Is there a popular perl library/framework for machine learning?
> 
> Thanks.


Have you tried searching the web for “perl machine learning”?

Some links from a Google search:

<http://www.perlmonks.org/?node_id=638391>
<http://search.cpan.org/~kwilliams/Algorithm-SVMLight/lib/Algorithm/SVMLight.pm>
<https://www.youtube.com/watch?v=Cdcx4lbUbes>



Jim Gibson

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




Re: How to pass all `dig` arguments to Net::DNS?

2017-01-21 Thread Jim Gibson

> On Jan 20, 2017, at 12:24 PM, al...@myfastmail.com wrote:
> 
> For my domain, I retrieve its DNS A-records from a local nameserver using
> 
>   /usr/bin/dig -t A @192.0.2.1 -k /etc/named/keys/T.key +noadditional 
> +dnssec +multiline +norecurs example.com
> 
> In my perl script, I can do the same using system()
> 
>   system( "/usr/bin/dig", "-t", "A", "\@192.0.2.1", "-k", 
> "/etc/named/keys/T.key", "+noadditional", "+multiline", "+norecurs", 
> "example.com" );
> 
> which lists all the keys to console.
> 
> I want to get at the same info using Perl, with the results in objects that I 
> can extract data from and assign to variables.
> 
> IIUC, Net::DNS is the right tool.
> 
> Reading the docs I don't understand how I'd pass all those bind dig-specific 
> arguments to Net::DNS.
> 
> What's the right syntax / usage for that query in Net::DNS?

You need to look at the documentation for the Net::DNS::Resolver, 
Net::DNS::Packet, and Net::DNS::Question modules as well as Net::DNS.

I have not used these modules before, but from the documentation I can suggest 
something like this to get started:

__CODE__
use strict;
use warnings;
use Net::DNS;

my $url = 'www.google.com';

my $resolver = new Net::DNS::Resolver(
nameservers => [ ‘192.0.2.1' ],
recurse => 0,
);

my $reply = $resolver->query($url) or die("Can't resolve $url $!");
my @question = $reply->question;

print "Reply:\n";
$reply->print;

__END__

It is possible that the Net::DNS family of modules do not support all of the 
options that the dig program does, but you will have to dig through the 
documentation and figure that out.

For example, you can print out individual sections like this:

print "\n;; HEADER SECTION\n";
$reply->header->print();

but I don’t see anything that supports an optional TSIG file equivalent to the 
-k option (I don’t know what that is, so can’t help with that).

Good luck!



Jim Gibson

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




Re: Perl file exists check

2016-11-10 Thread Jim Gibson

> On Nov 10, 2016, at 3:34 AM, jaceke  wrote:
> 
> I would like as argument of function use path with special characters then '' 
> are needed.
> That's why function adding apostrophe but after adding apostrofe file cannot 
> be found.

If the string value of the scalar variable that is passed to the subroutine 
contains special characters, those characters will be used as part of the file 
path. You do not need to surround the string with single or double quote 
characters to have those special characters interpreted by the operating system 
or file system.

You will need double-quote characters if you are trying to generate a string 
value with special characters within the source code of your program as a 
literal string.

> 
> For me it's strange why after declaration "my $f2 = '/etc/passwd';" paht can 
> be found but after adding apostrophe like that "$f1 = "'" . $f1 . "'";" paht 
> cannot be found.

That is because the apostrophe characters become part of the path string — not 
what you want.



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




Re: Perl file exists check

2016-11-10 Thread Jim Gibson
See inline comments below.

On Nov 10, 2016, at 3:15 AM, jaceke  wrote:
> 
> This example will be better :
> 
> #!/usr/bin/perl
> use strict;
> use File::Basename;
> use utf8;
> 

You should indent all blocks (subroutines, if statements, loops, etc.) to make 
it easier to read and follow the structure of your program.

> sub escMe($) {
> my $f1 = shift;
> my $f2 = '/etc/passwd';
> my $f3 = "'/etc/passwd'";
> my $f4 = '/etc/passwd';
> 
> $f1 = "'" . $f1 . "’";

This line adds apostrophes at the beginning and end of the file path being 
passed into the subroutine. You do NOT want to do that!

> 
> if($f1 eq $f2) {
> print("Files are same $f1$f2\n");
> } else  {
> print("Files are NOT same $f1$f2\n");
> }

$f1 contains this:   ‘/etc/passwd’
$f2 contains this:  /etc/passwd

One has single quotes and the other does not. They are not the same.

Let’s use the constructs q() and qq() for better readability. q(abc) is the 
same as ‘abc’, and qq(xyz) is the same as “xyz”. qq() allows interpolation of 
variables and escape sequences, q() does not.

> if (-e $f1)
> {
> printf "File exist $f1 !\n";
> } else {
> printf "File not exist $f1 !\n";
> }

The file q(‘/etc/passwd’), which has two single-quote characters, one at the 
beginning and one at the end, does not exist.

> 
> if (-e '$f2')
> {
> printf "File exist $f2 !\n";
> } else {
> printf "File not exist $f2 !\n";
> }

You are testing for the existence of a file with the name q($f2). In other 
words, the file name (or path) has three characters in it: dollar sign, eff, 
two. That file does not exist (in the current directory).

> 
> if (-e '$f3')
> {
> printf "File exist $f3 !\n";
> } else {
> printf "File not exist $f3 !\n";
> }

Same problem. q($f3) does not exist.

> 
> if (-e '$f4')
> {
> printf "File exist $f4 !\n";
> } else {
> printf "File not exist $f4 !\n";
> }

Same problem. q($f4) does not exist.

> if (-e '/etc/passwd')
> {
> printf "File exist !\n";
> } else {
> printf "File not exist !\n";
> }
> 

The file q(/etc/passwd) does exist.

> return $f1;
> }
> 
> escMe("/etc/passwd");
> 
> 
> 
> Output:
> Files are NOT same '/etc/passwd'/etc/passwd
> File not exist '/etc/passwd' !
> File not exist /etc/passwd !
> File not exist '/etc/passwd' !
> File not exist /etc/passwd !
> File exist !
> 


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




Re: Perl file exists check

2016-11-10 Thread Jim Gibson
On Nov 10, 2016, at 2:30 AM, jaceke  wrote:
> 
> Hi,
> how can I check if file exist or not ?
>  
> Here's a short test/example:
>  
> if (-e '/etc/passwd')
> {
> printf "File exist !\n";
> } else {
> printf "File not exist !\n";
> }
>  
> That works great !
>  
> but next a short test/example:
>  
> my $f1 = '/etc/passwd';
>  
> if (-e $f1)
> {
> printf "File exist !\n";
> } else {
> printf "File not exist !\n";
> }
>  
> and that NOT working ! Why ?
>  
> I use quotes because my path contain special characters.

Both of those versions work on my system. There is no reason for the version 
using a scalar variable holding the file path not to work.

Can you post a complete, short, working program that you think does not work?


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




Re: calculate within a loop

2016-09-12 Thread Jim Gibson

> On Sep 12, 2016, at 6:24 AM, Nathalie Conte  wrote:
> 
> Dear all,
> 
> Thanks a lot for the codes various people which all work perfectly!! I have 
> also discover some useful functions (eval and state) which can also be very 
> helpful for this kind of data.
> 
> In the light of this, my dataset got more complicated, now there are 3 layers 
> of hashes and I need now to calculate across those hashes for each name, 
> I have tried to apply some of the code structure which were kindly provided 
> and worked well for my first question, although as the data structure is now 
> more complicated and I need to assess the data accross hashes makes it more 
> complex and I din’t manage to get  a solution for this. Again, any help would 
> be greatly appreciated.
> ##
> 
> 
> 
> For each $name (100 and 101)- there are 3 levels, x, y and z -Times are 1,3,5 
> for all datasets, across x, y and z .

You call the second level keys “levels” here, but in your code the variable you 
use to hold these key values is $subject. What you call “times” here are held 
in a variable called $values. That is confusing. It is better if your variable 
names describe what values they hold, e.g. $level, $time.

> What needs to be calculated now with this more complex structure,  is  for 
> each name, a calculation across the 3 hashes, for the 3 times.
> 
> for 100:
> first line : no action
> second line : should reflect the difference between time 3 and time 1 across 
> x,y and z (x3-x1)+(y3-y1)+(z3-z1)
> time :3 - 1 =2, 
> value: calculation:  x (value 3(117)-value 1(97) + y (value 3 (89)) - value 1 
> (88)) + z (value 3 (97) - value 1 (95))
> total should be : 117-97 + 89-88 +97-95 =13 

I think that should be 23, because (117-97) is 20.

> third line: should reflect difference between time 5 and time 3 AND time 5 
> and time 1
> time : 5-3, and 5-1
> value: calculation: difference between time 5 and time 3 : x (-value5 (107) - 
> value 3(117)) + y (value5 (99)- value 3 (89)) + z (value 5 (94) - value 3 
> (97) ) = -3 total
>   difference between time 5 and time 1 : x (-value5 (107) - 
> value 1(97)) + y (value5 (99)- value 1 (88)) + z (value 5 (94) - value 1 (95) 
> ) = 20 total

So it looks like you have a three-level hash of values (grades?) indexed by 
name (‘100’, ‘101’), level (‘x’, ‘y’, ‘z’), and time (1, 3, 5). For each name 
you want to iterate over pairs of times and perform calculations done by 
grouping the grades according to levels.

The first thing to notice is that you need to reorganize your hash so you can 
iterate over names and times.

> 
> ###
> my partial code,
> #!/usr/local/bin/perl
> use strict;
> use warnings;
> use feature 'state';
>  
> use Data::Dumper qw(Dumper);
> my %hall;
> 
> $hall{"100 "}{'x'}{1}   = 97;
> $hall{"100 "}{'x'}{3}= 117;
> $hall{"100 "}{'x'}{5}= 107;
> $hall{"100 "}{'y'}{1}   = 88;
> $hall{"100 "}{'y'}{3}  = 89;
> $hall{"100 "}{'y'}{5}  = 99;
> $hall{"100 "}{'z'}{1}  = 95;
>  $hall{"100 "}{'z'}{3}  = 97;
>  $hall{"100 "}{'z'}{5}  = 94;
> $hall{"101 "}{'x'}{1}   = 197;
> $hall{"101 "}{'x'}{3}= 1117;
> $hall{"101 "}{'x'}{5}= 1107;
> $hall{"101 "}{'y'}{1}   = 188;
> $hall{"101 "}{'y'}{3}  = 189;
> $hall{"101 "}{'y'}{5}  = 199;
> $hall{"101 "}{'z'}{1}  = 195;
>  $hall{"101 "}{'z'}{3}  = 197;
>  $hall{"101 "}{'z'}{5}  = 194;
>  
> print Dumper \%hall;
> print "\n";
> 
> foreach  my $name ( sort keys %hall) {
> print "name.$name\n";
> foreach  my $subject (sort keys %{ $hall{$name} }) {
> print "suject.$subject\n";
> 
>   foreach  my $values  ( sort  keys %{ $hall{$name}{$subject}}) {
> state ($lgrade,$lsubject,$lname,$ltimes);
> 
>my $grade = $hall{$name}{$subject}; 
> print "grade is .$grade\n"; # this is not working and gives a reference!

%hall has three levels of hashes. So any value of %hall with only two indices 
will be a reference to a hash. if you want the scalar grade values, you must 
supply three indices.

>   my $times = $hall{$name}{$subject}{$values};
> print "time is .$times\n";
>   
> if (eval { $lgrade and $lname eq $name }) { 

Why the eval? You can evaluate logical expressions without doing the eval.

> 
> my ( $grade_diff, $times_diff) = ( $grade - $lgrade, 
> $times-$ltimes);
> print "$name,  
> $grade-$lgrade=$grade_diff:$name,$times-$ltimes=$times_diff \n";
> }
> ($ltimes, $lgrade,$lname) = ($times, $grade,$name);
> }
> }
> }

Try this:

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

my %hall;

$hall{"100 "}{'x'}{1} =   97;
$hall{"100 "}{'x'}{3} =  117;
$hall{"100 "}{'x'}{5} =  107;
$hall{"100 "}{'y'}{1} =   88;
$hall{"100 "}{'y'}{3} =   89;
$hall{"100 "}{'y'}{5} =   99;
$hall{"100 "}{'z'}{1} =   95;
$hall{"100 "}{'z'}{3} =   97;
$hall{"100 "}{'z'}{5} =   94;
$hall{"101 "}{'x'}{1} =  197;
$hall{"101 "}{'x'}{3} = 1117;
$hall{"101 "}{'x'}{5} = 1107;
$hall{"101 

Re: calculate within a loop

2016-09-10 Thread Jim Gibson

> On Sep 9, 2016, at 8:54 AM, Nathalie Conte  wrote:
> 
> Hello, 
> I have a question about making a calculation within a loop
> 
> I have a hash of hashes
> ##
> #!/usr/bin/perl
> use strict;
> use warnings;
>  
> use Data::Dumper qw(Dumper);
>  
> my %grades;
> $grades{"Foo "}{1}   = 97;
> $grades{"Foo "}{2}= 107;
> $grades{"Peti "}{1}   = 88;
> $grades{"Peti "}{3}  = 89;
> $grades{"Peti "}{4}  = 99;
>  
> print Dumper \%grades;
> print "\n";
>  
> foreach my $name (  keys %grades) {
> foreach my $subject (sort {$a <=> $b} keys %{ $grades{$name} }) {
> print "$name, $subject: $grades{$name}{$subject}\n";
> }
> }
> 
> ##
> output is 
> $VAR1 = {
>   'Peti ' => {
>'4' => 99,
>'1' => 88,
>'3' => 89
>  },
>   'Foo ' => {
>   '1' => 97,
>   '2' => 107
> }
> };
> 
> Peti , 1: 88
> Peti , 3: 89
> Peti , 4: 99
> Foo , 1: 97
> Foo , 2: 107
> ###
> Now, what I would like to achieve:
> I want to make a calculation, in each $name (Peti and Foo), calculate:
> for Peti:
> first line : no action
> second line -(minus) 1st line:
> print subject 3-1=2, 89-88=1
> third line - 2nd line:
> print subject 4-3=1, 99-89=10
> 
> for foo:
> first line : no action
> second line -(minus) 1st line:
> print subject 2-1=2, 107-97=10
> 

For each $name, declare two variables ($prev_subject and $prev_grade below) to 
hold the subject and grade. These variables will be undefined during the first 
pass through the inner loop:

for my $name ( keys %grades ) {
  my $nameref = $grades{$name};  # do one hash lookup
  my( $prev_subject, $prev_grade );
  for my $subject ( sort keys %{$nameref} ) { # {$a<=>$b} is the default for 
sort
my $grade = $nameref->{$subject};
if( defined $prev_subject ) {
  my $subject_delta = $subject = $prev_subject;
  my $grade_delta = $grade - $prev_grade;
  print "$name:  $subject_delta:  $grade_delta\n";
}
$prev_subject = $subject;
$prev_grade = $grade;
  }
}



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




Re: having trouble understanding the built-in Perl sort with regards to mixed numbers and strings

2016-06-17 Thread Jim Gibson
If you want to sort your data numerically, then the data must look like a 
number. Your data is mixed numerical and alpha data, hence the error message. 
You first need to extract the numerical parts of your data records and compare 
just those parts.

The first step would be to write a sort routine that extracts the numerical 
parts of the two key variables $a and $b, e.g., $anum and $bnum, and returns 
the value of the expression $anum <=> $bnum ( or $bnum <=> $anum if you want to 
reverse the order). 

That is not the most efficient way to solve this problem, as you are extracting 
the numerical parts more often than necessary, but it is a start. Try that and 
let us know if you want more help.

Once you get that working, you can write a Schwartzian transform that will 
extract the numerical values only once for each record.

> On Jun 17, 2016, at 2:41 PM, Kenneth Wolcott  wrote:
> 
> On Fri, Jun 17, 2016 at 2:33 PM, Kenneth Wolcott
>  wrote:
>> Hi;
>> 
>>  I'm having trouble understanding the built-in Perl sort with regards
>> to mixed numbers and strings
>> 
>>  I'm looking at http://perldoc.perl.org/functions/sort.html
>> 
>>  I have an array that I want to have sorted numerically and descending.
>> 
>>  The array is composed of elements that look like the following regex:
>> 
>>  ^\d+\t\[a-zA-Z0-9]+$
>> 
>>  I always have "use strict" at the top of my Perl scripts.
>> 
>>  If I try:
>> 
>>my @articles = sort {$b <=> $a} @files;
>> 
>>  I get error(s)/warning(s) that the data is not numeric.
>> 
>>  if I try:
>> 
>>  my @articles = sort {$b cmp $a} @files;
>> 
>>  I will get numbers sorted as letters, not numerically.
>> 
>>  I tried to understand the sort perldoc page further down, but did
>> not grok it at all.
>> 
>>  What I did as a workaround was to implement my own extremely
>> brute-force sort routine, which works, but is very ugly.
>> 
>>  Since I have very few elements (perhaps as many as a couple dozen),
>> the inefficiency is immaterial.
>> 
>>  I'd rather that my code be correct, intuitive and elegant (and efficient).
>> 
>> Thanks,
>> Ken Wolcott
> 
> Addendum:
> 
> It appears that when the sequence of digits is the same length in all
> instances that the data will be sorted correctly, but when the length
> of the sequence of the digits is not the same in the entire data set,
> that is when the sort results will be incorrect.
> 
> My most current data with this reverse character sort mechanism works
> correctly, but I'd like it to work in all cases.
> 
> -- 
> 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: Script to fork, send data to parent via a tcp conn

2016-05-16 Thread Jim Gibson

> On May 15, 2016, at 5:05 AM, Unknown User  wrote:
> 
> The port is not in use before i run the script. It is in use when i
> run it. However the problem is that only one iteration runs. I
> expected all to run.

Your ‘listen’ statement is in a loop. Therefore, the second time through the 
loop, the socket will be busy. As Uri suggested, you need to do the listen 
before the loop so you only do it once. Each iteration of the loop should fork, 
and the child branch should connect to the socket created by the parent 
process. The parent branch should do nothing in the loop. At some point, you 
will want to start waiting for the child branches to end and not exit the 
program until they have all completed running.

See ‘perldoc perlipc’ for examples of parent and children processes 
communicating through a socket.


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




Re: Counter Help

2016-02-09 Thread Jim Gibson

> On Feb 9, 2016, at 6:08 AM, James Kerwin <jkerwin2...@gmail.com> wrote:
> 
> Afternoon all,
> 
> I have the following problem:
> 
> I have an array containing a list of non-unique strings. eg:
> 
> @array Contains:
> 
> 11_
> 22_
> 33_
> 33_
> 33_
> 44_
> 44_
> 55_
> 
> What I would like to do is number each element of the array to look as 
> follows:
> 
> 11_1
> 22_1
> 33_1
> 33_2
> 33_3
> 44_1
> 44_2
> 55_1
> 
> I have so far tried to use "exists", while loops and all the usual stuff as 
> it seemed very simple at first. My attempts have mostly focused on equating 
> the current element of the array with the previous one and asking if they are 
> equal and then taking action. I just can't get the logic right though. I keep 
> getting them all numbered sequentially from 1 to 10 or they all end in "_2" 
> or alternating "_1" and "_2" If anybody could shed even the smallest glimmer 
> of light on how to solve this I'd be really grateful.

You should define a hash with the strings as keys and the number of strings 
encountered in the array so far as the hash value. You can then add the number 
to each string as you iterate over the array and increment the hash value count.


Jim Gibson
j...@gibson.org




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




Re: Counter Help

2016-02-09 Thread Jim Gibson

> On Feb 9, 2016, at 6:46 AM, James Kerwin  wrote:
> 
> Thank you both very much for your help. I'll investigate this way when I get 
> home later (I'm a bit wary of hashes because they're weird).

Here is a solution using a hash:

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

my @array = qw{
   11_
   22_
   22_
   33_
   33_
   33_
   44_
   44_
   55_
};

my %count;
for my $element ( @array ) {
  $element .= ++$count{$element};
}

print "Array:\n\n  ". join("\n  ",@array) . "\n”;

__END__

Note that the array needn’t be sorted for this method to work.
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Storing Output file.

2016-01-28 Thread Jim Gibson

> On Jan 28, 2016, at 1:37 AM, Frank Larry <frankylarry2...@gmail.com> wrote:
> 
> Hi Team,
> 
>  could you please let me? i have a file which contains "Debug", i would like 
> to replace debug to "Error", when i ran the below program the out showing 
> Error message but how to save the output with new changes. Could you please 
> tell me how to fix it?

The way to do this within a larger Perl program is to open a new output file, 
copy all of the possibly-modified lines to this file. Then you can rename the 
new file to the same name as the old file, and perhaps rename the old file as 
well and keep it around as a backup.

> 
> open(FILE, "<filter.txt") or die "Can’t open $!\n”; 

The three-argument version of open is preferred here, and let’s put the file 
name in a variable and use a lexical variable for the file handle (untested):

my $filename = ‘filter.txt’;
open( my $in, ‘<‘, $filename ) or die(“Can’t open $filename for reading: $!”);

# create a new file
my $newfile = $filename . ‘.new’;
open( my $out, ‘>’, $newfile ) or die(“Can’t create $newfile: $!”);

> 
> while($line = ){

while( $line = <$in> ) {
 
> 
>print "Before substituting: ", $line ,"\n"; 
> $line =~ s/Debug/Error/g; 
> print "After substituting : ", $line , "\n”; 

print $out $line;
>   
> }  
> 
> close(FILE);

close($in);
close($out) or die(“Error writing to output file $newfile: $!”);

# rename the old file
my $savefile = $filename . ‘.sav’;
rename $filename, $savefile;

# rename the new file
rename $newfile, $filename;

Jim Gibson
j...@gibson.org




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




Re: remove from mailing list

2015-11-26 Thread Jim Gibson

> On Nov 26, 2015, at 7:06 AM, Parysatis Sachs  wrote:
> 
> Hey, 
> 
> can you please remove me from the mailing list?
> 
> Thanks!

To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@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 interpolate a hash in a string

2015-11-03 Thread Jim Gibson

> On Nov 3, 2015, at 2:03 PM, David Emanuel da Costa Santiago 
>  wrote:
> 
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA256
> 
> 
> Hello all.
> 
> I'm trying to interpolate a hash value in a string but i got stuck.
> I already tried with eval, without any success… 

Show us what you tried.

> I have two conf files in the form
> conf file 1:
> option=value
> option2=value2
> 
> conf file 2:
> property=propertyValue
> property2=propertyValue2
> 
> I'm loading these files into a hash. But the problem is that i want to
> access, for example on conf file 2, properties from conf file 1:
> 
> property3=$HASH{option2}

is that literally what appears in file 2?

> So i'm getting the hash for conf file 2:
> 
> %PROPERTIES=(property=>"propertyValue",  property2=> "propertyValue2",
> property3=> "$HASH{option2}" );
> 
> but what i want is:
> %PROPERTIES=(property=>"propertyValue",  property2=> "propertyValue2",
> property3=> "value2" );
> 
> 
> this is how i'm reading the files:
> 
> sub _read_conf_file{
>  open my $FH, '<', shift @_;
>  while(<$FH>){
>chomp;
>s/\#.*//;
>/(\S+)\s*=\s*(.+)/;
>next if (!defined $1 || !defined $2);
>$OPTS{$1}=$2;
>  }
>  close $FH;
> }
> 
> Does anybody knows how to do this?

Here is one way parsing each value with a regular expression:

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

my %file1 = ( A => 'A', B => 'B' );

my %HASH;
_read_conf_file();

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

sub _read_conf_file{
  open my $FH, '<', shift @_;
  while(my $line = ) {
next if $line =~ /^\s*#/;
chomp($line);
my( $key, $val ) = split(/=/,$line);
next unless defined $val;

if( $val =~ m{\$file1\{'(\w+)'\}} ) {
  $val = eval($val);
# you could also use the following line here instead (with some loss of 
generality)
# $val = $file1{$1};
   }
$HASH{$key}=$val;
 }
}
__DATA__
A=$file1{'B'}


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




Re: reading from socket

2015-08-11 Thread Jim Gibson

 On Aug 11, 2015, at 3:16 PM, Chris Knipe sav...@savage.za.org wrote:
 
 Lastly, you're reading from a socket so there's no guarantee that
 the buffer string is going to necessarily end at the termination
 boundary. Perhaps the protocol guarantees that, but the socket
 surely doesn't. You may need to look for that terminating
 sequence in the middle of the buffer.
 
 
 But isn't that exactly why we set things like autoflush(1) or $|=1?  After 
 the data stream has been sent from the server (i.e. CRLF.CRLF) the server 
 stops transmitting data and waits for the next command, so there's no chance 
 that a second data stream may be received by the client socket, at least not 
 until the client socket issues a new command.  

The TCP transmission protocol is not line-oriented, so, depending upon how the 
remote node has their socket configured, each buffer of data from the server 
could possibly contain multiple lines and may not end with a complete line. The 
packet containing the end of the partial line could be delayed or never arrive 
if the connection is broken.

Transmit and receive are asynchronous, so can be going on simultaneously. Your 
application protocol may require the server to wait for a command from the 
client before resuming transmission of the next packet, but that is not 
required by the TCP protocol.
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Perl multi threading

2015-08-01 Thread Jim Gibson

 On Aug 1, 2015, at 1:49 AM, bikram behera jobforbik...@gmail.com wrote:
 
 Hi Team,
 can you tell me about perl multi threading,  uses of multi threading with 
 examples. 

See ‘perldoc perlipc’ for all kinds of information about multi-threading with 
lots of example code.


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




Re: Yenc encoder performance

2015-07-31 Thread Jim Gibson

 On Jul 31, 2015, at 4:39 AM, David Emanuel da Costa Santiago 
 deman...@gmail.com wrote:
 
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA256
 
 
 
 Hello.
 
 
 Thanks for your reply.
 
 
 I remember that i did some performance tests and 
 
 $string = $string .something
 
 had better performance than 
 
 $string .= “something

Those two lines should result in exactly the same machine instructions. They 
are two different ways of writing the same thing. There should be no difference 
in perfomance.

 which matched the results of (link to stack overflow)
 http://stackoverflow.com/questions/3104493/performance-with-perl-strings

That post compares the following 3 ways of forming a long string (see the 
benchmark program posted by sebthebert):

1.
  $string = ‘A’
  $string .= ‘B’;
  $string. = ‘C’;

2.
  $string = ‘A’ . ‘B’ . ‘C’;

3.
  $string = join(‘’, (‘A’, ‘B’, ‘C’) );

It does not compare $string .= ‘X’ with $string = $string . ‘X’

Write and run your own benchmark comparing those two cases and post your 
results here.

(#2 turns out to be fastest, with #3 a close second)

In any case, you probably shouldn’t be worrying about such minor differences in 
execution speed. Reliability, accuracy, and ease of maintenance are much more 
important qualities for software to have. Operators such as ‘.=‘ permit shorter 
source code and fewer chances for errors.



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




Re: convert linear array to nested structure

2015-07-21 Thread Jim Gibson

 On Jul 21, 2015, at 12:40 PM, Simon Reinhardt si...@keinstein.org wrote:
 
 Hi Team,
 
 is there a ready solution to convert an linear array of hashrefs
 like this
 
 [ {level = 0, value = string1},
  {level = 1, value = string2},
  {level = 2, value = string3},
  {level = 2, value = string4}
 ]
 
 into the nested data structure
 
 [ {value = string1,
   kids = [
   {value = string2,
kids = [
{value = string3},
{value = string4}]}]}]
 
 ? Any pointer appreciated.

That is an unique data structure and transformation requirement (as most are), 
so you are not likely to find an existing set of code to do exactly what you 
want. However, the transformation should not be too difficult, so you should 
try to code up something yourself and ask for help if you get stuck or would 
like to optimize your solution.

If I were coding this, I would like to know how complicated the data structure 
could become. For example, will there be multiple entries at levels 0 and 1, 
and how sould they be handled? 

The data structure you have shown is not very efficient in tems of data 
storage. Is this the actual data structure, or is it part of something more 
complicated. For exampe, a more efficient use of space would be this, which 
uses nested arrays instead of hashes:

[ 
 [0, “string1],
 [1, “string2],
 [2, “string3],
 [2, “string4]
]


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




Re: Traversing directory recursively

2015-07-09 Thread Jim Gibson

 On Jul 9, 2015, at 8:27 AM, Nagy Tamas (TVI-GmbH) tamas.n...@tvi-gmbh.de 
 wrote:
 
 Hi,
  
 So I have a better version. But if it goes down in the recursion tree, at the 
 end it goes into infinite loop,
 because there is no other dir inside the last dir in the tree. At this point 
 it has to step back. But instead
 of stepping back it goes into infinite loop. Why?
  
 sub Traverse
 { 
 if( opendir(DIR, $dir) ) {
my @files = readdir(DIR);
closedir(DIR);
foreach my $file (@files) {
# generate XML here

$actualdir = $dir . \\ ;

next if (($file eq '.') || 
 ($file eq '..'));

print $file;
if((-d $actualdir.$file) and 
 ($file !~ /^\.\.?$/) and ($file ne .) and ($file ne ..)) {
# make dir 
 branch

$newpath = 
 $actualdir.$file;


 $writer-startTag(Folder, Name = $newpath);

 Traverse($newpath, $writer);

 $writer-endTag(Folder);
} else {
# make file 
 branch

 $writer-emptyTag(Object, Name = $actualdir.$file);  
 
}
}
 }
 }
  
 Tamas

It is because you are calling the Traverse() subroutine with two arguments to 
recurse a directory tree, but you are not using the arguments. Each call to 
Traverse uses the global $dir variable as the root of the tree, so it will 
never terminate.

You need a statement such as this near the top of your routine:

  my( $dir, $writer ) = @_;


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




Re: Fire and forget subs

2015-07-06 Thread Jim Gibson

 On Jul 6, 2015, at 9:43 AM, Unknown User knowsuperunkn...@gmail.com wrote:
 
 What is a good way to fire and forget a sub from a module in perl, in a non 
 blocking mode, preferably without forking or using threads.
 I may have to run the sub a few times to determine the approx delay for it to 
 run, so i suppose i need a blocking mode for it too. But afterwards, it can 
 run in non blocking mode.
 
 - Unknown

There is no way to call a subroutine and have it return immediately yet still 
do productive work in the background without using some sort of multi-tasking, 
i.e., forks or threads, on a single, normal computer.

Starting a separate process using fork is relatively easy. The problem is 
figuring out when the forked process is done and getting information back from 
it to the main program.

See ‘perldoc perlipc’ for ideas on creating and communicating with separate 
processes.


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




Re: Changing the structure of a hash

2015-06-17 Thread Jim Gibson
It seems that you are working with a two-dimensional array of numbers, so it is 
not clear why you are using a hash to store this data instead of an array of 
arrays.

What you seem to be asking for is to generate the transpose of the 
two-dimensional array. So the simplest approach would be to convert your hash 
into an array of arrays and calculate the transponse. Does that work for you?

 On Jun 17, 2015, at 10:48 AM, Anirban Adhikary anirban.adhik...@gmail.com 
 wrote:
 
 Hi List 
 
 I have a hash with the following data structure.
 KEY=[0]--  VALUE=[57 147 237 327 417 507 597 687 777 867 957 1047 1137 1227 
 1317 1407]
 KEY=[1]--  VALUE=[58 148 238 328 418 508 598 688 778 868 958 1048 1138 1228 
 1318 1408]
 KEY=[10]--VALUE=[67 157 247 337 427 517 607 697 787 877 967 1057 1147 1237 
 1327 1417]
 …

 Now you can see that for first key i.e. KEY 0 the values are from 57 to 1407. 
 But my target is to create another hash whose first key will be KEY0 but its 
 value will be from 57 to 66 that means for each value each column will be 
 changed as each row.
 
 How to implement this. Please provide some hints.
 
 Best Regards
 Anirban.
 


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




Re: Good books to study perl interpreter

2015-03-30 Thread Jim Gibson
The best book on Perl (in my opinion) is “Programming Perl, 4th ed.”, 
Christiansen, foy, Wall,  Orwant.

See “perldoc perlbook” for other recommendations, as well as 
http://books.perl.org


 On Mar 30, 2015, at 9:42 AM, rakesh sharma rakeshsharm...@hotmail.com wrote:
 
 Hi all
 
 Please suggest nice books to know perl interpreter. In depth books is that i 
 am looking for.
 
 Thanks
 Rakesh


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




Re: OTRS module

2015-03-26 Thread Jim Gibson

 On Mar 26, 2015, at 3:54 PM, Benjamin Fernandis benjo11...@gmail.com wrote:
 
 Hi,
 
 We are using otrs help desk system which is in fully perl. We require to 
 append automatic comment when our specific customer raise ticket to us. We 
 have iteam no for each customer.So when customer send mail and in body he 
 mentioned iteam code ( like 4322) , so otrs automatically checks sender 
 email id and then fetch iteam code from body and according to that otrs fetch 
 respective information from database or excel sheet and add comment to that 
 ticket.
 
 I can write logic out side of otrs. but i never tried to write any module for 
 3rd party applications.
 
 Can you please suggest me a way to do this.
 
 Thanks
 Ben

You don’t mention which  OTRS Help Desk system you are using, but a Google 
search turns up this one:

https://otrs.github.io/doc/manual/admin/stable/en/html/otrs.html

Is that the one?

Perl modules are installed as source code files, so you can modify the module’s 
source and add whatever functionality you need. The OTRS Help Desk looks like a 
fairly complicated system, so adding functionality without breaking it could be 
a significant task. In any case, it is probably outside the scope of a Perl 
beginner’s list.

Good luck.


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




Re: Spliting and creating small files from a main files based on line number

2015-03-25 Thread Jim Gibson

 On Mar 25, 2015, at 10:07 AM, Anirban Adhikary anirban.adhik...@gmail.com 
 wrote:
 
 Hi List
 I have a configuration file and I would like to split the main file into 
 multiple small files and push the small temp. files into an array. My config 
 file looks like this 
 
 GRC01;8;8;1;1;323U6_SIU-8;2048;2048;20;0;OFF
 (30 lines snipped)
 GRC01;335;335;32;32;335U6_SIU-335;2048;2048;20;0;OFF
 
 This config file has got 32 lines so I am planning to write a code which will 
 create four tmp. files out of the main config file. I have written the 
 following code.
 
 #!/usr/bin/perl
 use Tie::File;
 use strict;
 use warnings;
 
 my @config_file_contents;
 tie @config_file_contents, 'Tie::File', GRC01_TG_SCGR_IPM_LIST ###-- This 
 is main config file
   or die Can't open filename;
 
 my @tmp_config_array=@config_file_contents;
 untie @config_file_contents;
 my $last_element_index = $#tmp_config_array;
 my $counter = 1;
 my $start_index = 0;
 my $next_index = 8;
 
 for (my $i=0; $i= $last_element_index; $i++) {

You are iterating over all of the lines in the configuration file, which is 32. 
I think you only want to execute this loop four times, one for each subfile.

 print inside for loop\n;
 print START=$start_index\n;
 print NEXT=$next_index\n;
 my $file_to_write = GRC01_TG_SCGR_IPM_LIST_$counter;
 my @tmp_line_content = splice 
 (@tmp_config_array,$start_index,$next_index);
 open my $WFH,'',$file_to_write;
 foreach my $el (@tmp_line_content) {
 print EL=[$el]\n;
 next if /^\s*$/;
 print $WFH $el\n;
 }
 close($WFH);
 $start_index = ($next_index+1);
 $next_index  = ($start_index+8);
 $i = $start_index;
 $counter++;
 #   @tmp_line_content = undef;
 
 }
 
 while executing the code 4 tmp files are created but all of them are zero 
 byte. Though in the print for first time  EL  I am getting 8 lines and 
 second time EL prints 
 15 lines but line number 9-15 are skipped.Second time EL should start 
 printing from line number 9 instead it starts printing from line number 18.
 But the counters like $start_index,$next_index are incrementing properly.
 Also I am getting warning message splice() offset past end of array at 
 ./tie_file.pl line 22”

After the first four iterations of your outer loop, $start_index will be beyond 
the last element index in @tmp_config_array, and @tmp_line_content will be 
empty. That is why your subfiles have zero bytes. The subfiles may be correct 
after the first four iterations, but they are getting overwritten in the 
subsequent 28 iterations.


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




Re: How to sort a file based on numerical values exists in each line

2015-03-24 Thread Jim Gibson

 On Mar 24, 2015, at 3:42 AM, Anirban Adhikary anirban.adhik...@gmail.com 
 wrote:
 
 Hi List
 I have a file like this.
 RXMOI:MO=RXOTRX-473-0,SC=0,DCP1=178,SIG=SCCONC,DCP2=179186,TEI=0;
 RXMOI:MO=RXOTRX-473-5,SC=0,DCP1=223,SIG=SCCONC,DCP2=224231,TEI=5;
 RXMOI:MO=RXOTRX-473-1,SC=0,DCP1=187,SIG=SCCONC,DCP2=188195,TEI=1;
...

 This file is from a testing environment. But in production environment this 
 file can be more than 500 lines. So my goal is to sort the file based on the 
 bold numbers and create a new file.
 This is required for data validation. If the file is not in sorted order then 
 it will be very difficult to validate the file manually.

This is a typical application of a technique called a Schwartzian Transform 
(google it). You can combine all of the steps of extracting the keys and 
original line into an anonymous array, sorting the array references, and 
extracting the original line into one command:

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

my @lines = DATA;

my @sorted = 
map { $_-[2] }
sort { $a-[0] = $b-[0] or $a-[1] = $b-[1] }
map { [ /RXMOI:MO=RXOTRX-(\d+)-(\d+)/, $_ ] }
@lines;

print for @sorted;

__DATA__
RXMOI:MO=RXOTRX-473-0,SC=0,DCP1=178,SIG=SCCONC,DCP2=179186,TEI=0;
RXMOI:MO=RXOTRX-473-5,SC=0,DCP1=223,SIG=SCCONC,DCP2=224231,TEI=5;
RXMOI:MO=RXOTRX-473-1,SC=0,DCP1=187,SIG=SCCONC,DCP2=188195,TEI=1;
RXMOI:MO=RXOTRX-1-8,SC=0,DCP1=250,SIG=SCCONC,DCP2=251258,TEI=8;
RXMOI:MO=RXOTRX-1-2,SC=0,DCP1=196,SIG=SCCONC,DCP2=197204,TEI=2;
RXMOI:MO=RXOTRX-1-0,SC=0,DCP1=178,SIG=SCCONC,DCP2=179186,TEI=0;
RXMOI:MO=RXOTRX-460-9,SC=0,DCP1=259,SIG=SCCONC,DCP2=260267,TEI=9;
RXMOI:MO=RXOTRX-460-4,SC=0,DCP1=214,SIG=SCCONC,DCP2=215222,TEI=4;
RXMOI:MO=RXOTRX-460-8,SC=0,DCP1=250,SIG=SCCONC,DCP2=251258,TEI=8;


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




Re: How to sort a file based on numerical values exists in each line

2015-03-24 Thread Jim Gibson

 On Mar 24, 2015, at 7:27 AM, Anirban Adhikary anirban.adhik...@gmail.com 
 wrote:
 
 Hi Jim
 
 In your code there is some hard coded value [ /RXMOI:MO=RXOTRX
 But I can't put any hard coded value since I use this code as a function and 
 pass the filename as an argument.
 As you can see in my code there is no hard coded value.

You can modify the regular expression used to extract the sort values depending 
upon the circumstances under which your function will be used. I was just 
giving an example of how to combine all of the individual steps into one 
command. I based the regex I used on the sample data you had provided.

If you have any lines that do not match the regular expression, then the method 
I showed will produce errors, as there will be no extracted values to sort on 
for those lines.

If I were writing a general purpose function, then I would not combine the 
steps as I have shown, but keep them as separate functions with any necessary 
error-checking and ilne filtering.


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




Re: Eclipse - How do I get back to the first splash screen

2015-03-13 Thread Jim Gibson

 On Mar 13, 2015, at 2:07 PM, Sherman Willden sherman.will...@gmail.com 
 wrote:
 
 I downloaded Eclipse and I was looking at the screens and in general just 
 messing with Eclipse. Now I can't find the first splash screen with the 
 tutorials, samples, and such. Also is there a help button on Eclipse?

It has been awhile since I first downloaded and installed Eclipse, but in the 
version (Indigo) I have on my system, the Help - Welcome menu item gets you to 
that initial splash screen with Overview, Samples, Tutorials, and What’s New. 
As far as a Help button, there is a Help menu. Does that have what you are 
looking for?



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




Re: use perl format data

2015-02-05 Thread Jim Gibson

 On Feb 5, 2015, at 6:53 PM, Wang, Zeng-Sheng (TS-GSD-China-ZZ) 
 zengsheng.w...@hp.com wrote:
 
 Dear Uri,
  
 First thanks for your kindly help and a read-friendly instruction, I will not 
 use $a and $b for variables. According to your explanation, I finish the code 
 as below:
 #!/usr/bin/perl -w
   2 use strict;
   3 open(FH,'',file1);
   4 my @first_file = FH;
   5 close (FH);
   6
   7 open(FH,'',file2);
   8 my @second_file = FH;
   9 close (FH);
 10
  11 open(FH,'',file3);
 12 my @third_file = FH;
 13 close (FH);
 14
  15 chomp @first_file;
 16 chomp @second_file;
 17 chomp @third_file;
 18
  19 my ($out_line,$number);
 20 $number = @first_file;
 21 $out_line='';
 22 for(0..$number){
 23 $out_line.= shift @first_file;
 24 $out_line.= \t.shift @second_file;
 25 $out_line.=\t.shift @third_file;
 26 $out_line.=\n;}
 27
  28 print $out_line;
  
 I realize my target, however, there are some warnings in the prompt, how can 
 I eliminate them? Why?
 perl format.pl
 Use of uninitialized value in concatenation (.) or string at format.pl line 
 23.
 Use of uninitialized value within @second_file in concatenation (.) or string 
 at format.pl line 24.
 Use of uninitialized value within @third_file in concatenation (.) or string 
 at format.pl line 25.
 a b c   x y z   1 2 3
 d e f   q w e n 3 4 5
 j p ka s d   8 9 2 1
  
 Thank you very much again.

In line 20, @first_file is evaluated in scalar context, which is the number of 
elements in the array, and assigned to $number. In line 22, your for loop is 
iterated for values 0 through $number. This results in $number+1 iterations. 
Therefore, during the last iteration, all of the elements of all three arrays 
have been exhausted, and your program is attempting to concatenate three 
undefined values to $out_line. Hence the three warning messages.

The easiest way to fix this is to iterate on values (0..$#first_file). 
$#first_file is the maximum index of the @first_file array.

In the longer term, you may want to add logic to your program to handle the 
case where the files have differing numbers of lines or you have more than 
three files.

There are numerous other improvements you can make to this program, if you are 
interested.



--
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 Jim Gibson

 On Jan 18, 2015, at 9:03 AM, Mike ekimduna...@gmail.com 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/ );

You can also use the capture variables $1, $2, $3, etc., which will contain the 
captured subexpressions:

 my $insult;
 if( $mech-text =~ m/Insulter\ (.*)\ Taken/ ) ) {
   $insult = $1;
 }


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




Re: share a variable between files

2014-10-08 Thread Jim Gibson
The ‘our’ statement associates a simple name with a package global variable in 
the current package. Therefore, if you want to make $var in file b.pl mean the 
package global variable $var in package a ($a:var), just put ‘our $var;’ after 
the ‘package a;’ statement in file b.pl (see below).

On Oct 8, 2014, at 7:35 AM, Hans Ginzel h...@matfyz.cz wrote:

 Hello!
 
 Let's consider following strip-down example:
 
 # file a.pl
 use strict;
 package a;
 our $var=1;
 warn var=$var;
 
 # file b.pl
 use strict;
 #no strict qw/vars/;
 require 'b.pl';
 package a;

our $var;

 warn var=$var;
 
 How to get rid of no strict qw/vars/; to not get message Global symbol
 $var requires explicit package name at b.pl, please? There is a package
 specification (package a;) in the b.pl file.
 
 Generally, I want to add a key to a global class hash variable (%opt)
 declared with our in a class module from another file.
 
 I realised, that there is possible without warning to define a subroutine
 in another package, but not to use a global variable from that package
 (=namespace).


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




Re: returning arrays

2014-09-09 Thread Jim Gibson

On Sep 9, 2014, at 2:09 PM, lee wrote:

 Jim Gibson jimsgib...@gmail.com writes:
 
 On Sep 8, 2014, at 3:13 PM, lee wrote:
 
 Shawn H Corey shawnhco...@gmail.com writes:
 
 On Mon, 18 Aug 2014 16:17:53 +0800
 # or
 
 sub myfunc {
 return [ 1, 2, 3 ];
 }
 
 Is there a difference to
 
 sub myfunc {
 return ( 1, 2, 3 );
 }
 
 The first example returns [ 1, 2, 3 ], which is a reference to a list with 3 
 elements. References are scalars.
 
 The second example returns ( 1, 2, 3 ), which is a list with 3 elements.
 
 So, yes, there is a difference.
 
 Hm, so what way of thinking is behind this, and how do you declare an
 array?

Perls 1-4 (I believe) did not have references. They were added with Perl 5, 
which allowed complex data structures not possible without them. Think array of 
arrays and hashes of hashes. Once references were introduced, a lot of new 
possibilities for passing arguments and returning values arose.

 my $i = 1;
 my $f = 2.5;
 my $s = 'string';
 my $list = (1, 2, 3);

That should be: my @list = ( 1, 2, 3 );

Some people make a distinction between 'list' and 'array'. A list is a sequence 
of scalar values indexed by an integer. An array is a variable whose value is a 
list (or something like that -- I don't really distinguish the two myself.)

 my $list_reference = [(1, 2, 3)];

That can be expressed more simply: my $list_reference = [ 1, 2, 3 ];

 my $dereferenced_list = $@list_reference;

That is incorrect. You probably mean either this:

my @dereferenced_list = @$list_reference;

or this:

my $list_reference = \@list;

or even this:

my $list_reference = \(1, 2, 3);

 my @artificial_array = $@list_reference;

There is nothing artificial about that array:

my @array = @$list_reference;

 my @true_array = ?

my @true_array = ( 1, 2, 3 );

In either case, the result is the same. @array and @true_array are both arrays 
with a set of values.

 
 
 I'm finding this very confusing.  What's the benefit of using extra
 designators for some types of variables (arrays) while not even having
 any at all for some others (lists)?

The designators are for named variables. Lists are like pure values, just like 
1.0 and string, Like all literal values, they do not need designators (names).

 Perl will not garbage-collect an element if there is a reference to
 it. So while the array name @x no longer is in scope once the
 subroutine has returned, the list that was the value of @x still
 exists in memory, and the reference returned by the subroutine will be
 valid.
 
 If the reference is not saved or copied, then the list will eventually get 
 garbage collected.
 
 Hmm, ok, strange ... good to know, though.

Not strange at all. If Perl knows there is no way to reference or access a 
value in memory, that value will get garbage collected. If there is a way, it 
won't. To do otherwise would either 1) leak memory, or 2) lead to invalid 
references.


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




Re: returning arrays

2014-09-09 Thread Jim Gibson

On Sep 9, 2014, at 2:57 PM, Shawn H Corey wrote:

 On Tue, 09 Sep 2014 23:09:52 +0200
 lee l...@yun.yagibdah.de wrote:
 
 my $i = 1;
 my $f = 2.5;
 my $s = 'string';
 my $list = (1, 2, 3);
 
 No, the count of items in the list gets stored in $list: $list == 3

Unless the thing on the right-hand-side of the assignment is a 'list' and not 
an 'array'. This is the one place I can think of where the distinction between 
'list' and 'array' actually makes a difference.

Compare this:

  my $n = ( 4, 5, 6 );

with this:

  my @a = ( 4, 5, 6 );
  my $n = @a;

(Don't try this with the list ( 1, 2, 3 ), either!)


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




Re: returning arrays (was: Re: return the list content)

2014-09-08 Thread Jim Gibson

On Sep 8, 2014, at 3:13 PM, lee wrote:

 Shawn H Corey shawnhco...@gmail.com writes:
 
 On Mon, 18 Aug 2014 16:17:53 +0800
 Ken Peng o...@dnsbed.com wrote:
 
 sub myfunc {
  my @x=(1,2,3);
  return \@x;
 }
 
 # or,
 
 sub myfunc {
  my @x=(1,2,3);
  return [@x];
 }
 
 # or
 
 sub myfunc {
  return [ 1, 2, 3 ];
 }
 
 Is there a difference to
 
 sub myfunc {
  return ( 1, 2, 3 );
 }

The first example returns [ 1, 2, 3 ], which is a reference to a list with 3 
elements. References are scalars.

The second example returns ( 1, 2, 3 ), which is a list with 3 elements.

So, yes, there is a difference.

 ?  And my understanding was/is that in
 
 sub myfunc {
  my @x=(1,2,3);
  return \@x;
 }
 
 a reference would be returned to an array that ceases to exist when the
 function returning it has finished.  At the point the function returns
 to, there isn't anything left the reference could refer to.
 
 Or is there?

Perl will not garbage-collect an element if there is a reference to it. So 
while the array name @x no longer is in scope once the subroutine has returned, 
the list that was the value of @x still exists in memory, and the reference 
returned by the subroutine will be valid.

If the reference is not saved or copied, then the list will eventually get 
garbage collected.


--
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-19 Thread Jim Gibson

On Aug 19, 2014, at 9:12 AM, Manuel Reimer wrote:

 Hello,
 
 there are many very good examples on how to execute perl code from C. For 
 example the following tutorial is very helpful:
 
 http://perldoc.perl.org/perlembed.html
 
 But it only shows calling from C to perl.
 
 What I want to do is to create a function in C code and somehow export it to 
 my embedded perl interpreter. Then I want to be able to call this C function 
 from perl code.
 
 Can someone point me to a good example on how to do this?
 
 Thank you very much in advance.
 
 Greetings,
 
 Manuel

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.

There is a tutorial about XS at the same website (or via the perldoc 
command-line program):

http://perldoc.perl.org/perlxstut.html

Good luck!


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




Re: What's wrong with this program?

2014-08-06 Thread Jim Gibson

On Aug 6, 2014, at 10:55 AM, ESChamp wrote:

 The program begins
 
 #!/usr/bin/perl

You really should add these two lines:

  use strict;
  use warnings;

here and correct the mistakes they reveal.


 use Tie::File;
 use File::Copy 'copy';
 use File::Spec;
 
 my $copy=00-copy.htm;
 my $recapfile=00recap.txt;
 my $htmfile=00.htm;
 my $ct;
 
 tie my @bfile, 'Tie::File', $recapfile or die cannot tie recapfile and
 bfile $!;
 tie my @hfile, 'Tie::File', $copy or die cannot tie copy and hfile $!;
 
 ## hfile is the array of the lines of htmfile
 #
print $copy \n;
print hfile: --$hfile-- \n;
print bfile: --$bfile-- \n;

You are printing $hfile and $bfile, which are separate variables from @hfile 
and @bfile and are undefined. You should print $#hfile and $#bfile here 
instead, which will show you the largest indices of the two arrays.

for ($ct = 0; $ct  $#hfile; $ct++){

You probably want '$ct = $#hfile' as your condition here, since $#hfile is the 
greatest index of @hfile and not the number of elements, so your loop will not 
print the last element of @hfile.

   print $hfile[$ct] \n;
   }
 
 The output looks like this
 
 00-copy.htm
 hfile: 
 bfile: 

You can also use these to print the contents of an array:

print @hfile;

print for @hfile;

for ( @hfile ) {
  print;
}


 I thought that $recapfile would be tied to @bfile and $copy to @hfile.
 That is, that each line of $recapfile would become an element of the
 bfile array, etc.
 
 What have I done wrong?

Nothing major. Your program should work (with a few minor bugs). Are you sure 
there is data in 00-copy.htm?



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




Re: Suddenly.... Part 2

2014-07-31 Thread Jim Gibson

On Jul 31, 2014, at 12:02 PM, ESChamp wrote:

 John W. Krahn wrote on 7/31/2014 3:11 AM:
 Peter Holsberg wrote:
 I think I've isolated the section that is not doing what I want.
 
 open (FHIN, $recapfile) or die $!;
 
 That would be better as:
 
 open my $FHIN, '', $recapfile or die Cannot open '$recapfile' because: 
 $!;
 
 Thanks, John. As this is a beginners list and I'm an elderly beginner
 who is an occasional perl user, what makes that better?

It is better because 1) it uses the three-argument form of open instead of the 
two-argument version (the two-argument version has known risks), 2) it doesn't 
put the variable containing the file name in superfluous double-quotes, 3) it 
adds the file name to the error message, and 4) it uses a local lexical 
variable instead of a global bareword package variable.


 my $indexb; ## for the recapfile array
 my $ofile;
 
 You never use this variable, it should be:
 
 my @ofile;
 
 Could you kindly explain that?

You are declaring a scalar variable $ofile, but in your code below you use the 
array variable @ofile. These are not the same thing. If you put 'use strict;' 
at the beginning of your program, Perl will inform you that you have not 
declared @ofile.


 # Create new array containing all the lines of recapfile up to
 # the string RESULTS OF BOARD 1
 
 XYZZY:
 while (FHIN)
 {
 last XYZZY if  / RESULTS OF BOARD 1/;
 chomp;
 $ofile[$indexb++] .= $_;
 
 That would be better as:
 
 push @ofile, $_;
 }
 close FHIN;
 
 Exactly what lines would yours replace? Why would that be better?

  push @file, $_;

replaces 

  $ofile[$indexb++] .= $_; 

This is better because 1) it is simpler and therefore less likely to contain an 
error, 2) uses a Perl built-in function instead of hand-crafted code, 3) 
doesn't use an additional variable ($indexb), 4) doesn't use the unnecessary 
concatenation operator '.=' where a simple assignment '=' would do.

  x .= y

is equivalent to

  x = x . y

While this works in your case because the elements of @ofile are all undefined, 
and concatenating a string to an undefined value results in a simple 
assignment, it is a superfluous operation.



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




Re: Suddenly this script is not working!

2014-07-30 Thread Jim Gibson

On Jul 29, 2014, at 11:00 PM, ESChamp wrote:

 Jim Gibson wrote on 7/29/2014 10:08 PM:
 
 
 This is all speculation because you have not provided us with your exact 
 program and data files.
 
 I was warned not to post a 3000 line data file and a 150 line program,
 but if you'd like me to send them to you off-line, I will.

The best way to get help in this situation is to reduce your program and data 
down to about 10 lines each, but still containing the statements that are 
giving you problems. Then you can post both program and data here, and people 
will be able to run your exact code and tell you exactly what is going wrong. 
In the process of extracting the problem areas from your original program you 
might well fix the problem yourself.

Since we don't have the exact code and data, we are all speculating and 
guessing what might be the cause.

Hope you've got your program working by now.


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




Re: Why Does the Following Not Work?

2014-07-30 Thread Jim Gibson

On Jul 30, 2014, at 1:23 PM, Martin G. McCormick wrote:

 I thought that one could test for an empty or undefined array
 against the @arrayname but it looks like doing that always
 succeeds if it is set with my or our @arrayname.

You can test for an empty or an undefined array. Any array in scalar context 
will evaluate to the number of elements of the array. An 'if' or 'unless' 
statement will put the testing expression into scalar context, so in the 
statment 'if(@array)', @array will be evaluated in scalar context. If the array 
has any elements, even just one that is undef, @array will evaluate  to true.

There must be something else going on.



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




Re: Suddenly this script is not working!

2014-07-29 Thread Jim Gibson

On Jul 28, 2014, at 3:59 PM, ESChamp esch...@gmail.com wrote:

 Suddenly, without warning or error messages, the script below is
 producing null for values of $hfile and $bfile!

What are $hfile and $bfile? You don’t show them in your script. You show two 
arrays: @hfile and @bfile, but those are not the same as the scalar variables 
$hfile and $bfile.

When asking other people for help, it is best to reduce your program down to 
the shortest version that illustrates your problem. People can help you fix 
that, and you can then apply the fix to your actual program.

In this case, it is impossible to help you with the above stated problem, 
because the variable about which you are complaining do not exist in your 
program.

If you actually mean @hfile and @bfile, you say that $copy is correct. Are the 
contents of the file named by $copy also correct?

 The script begins:
 
 #!/usr/bin/perl
 
 use Tie::File;
 use File::Copy 'copy';
 use File::Spec;
 
 
 and further down, it has:
 
 # Tie it to an array
 #
 (my $copy = $htmfile) =~ s/(\.htm)\z/-Copy$1/i;
 copy $htmfile, $copy;
 tie my @hfile, 'Tie::File', $copy;
 tie my @bfile, 'Tie::File', $recapfile;
 
 ## hfile is the array of the lines of htmfile
 #
print $copy \n;
print hfile: 1--$hfile-- \n;
 
 $copy's value is correct.
 
 I'm on a Windows 7 machine. Should I have the Windows full pathname for
 perl.exe at the top

No, because if you are getting any output at all from your Perl program, then 
the program has been found and executed by the operating system.

 Happy to send the entire script to anyone who would like to see it.

Produce a shorter version of the script that demonstrates the problem and post 
it here for all to see.


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




Re: Suddenly this script is not working!

2014-07-29 Thread Jim Gibson

On Jul 29, 2014, at 5:12 PM, ESChamp esch...@gmail.com wrote:

 ESChamp wrote on 7/28/2014 6:59 PM:
 Suddenly, without warning or error messages, the script below is
 producing null for values of $hfile and $bfile!
 
 The script begins:
 
 
 
 Let me backtrack and provide some background information.
 
 This script processes two files, recapfile, a plain text file, and copy,
 and HTML-formatted file.
 
 It reads copy into an array, and recapfile into another array. Then it
 writes a new array which contains all the initial lines of the recapfile
 array from the first line down to but not including the first line
 containing / RESULTS OF BOARD 1/

Most of that information is superfluous. You need to concentrate on the precise 
problem that you are having.

 
 And here is where it goes wrong ('No pre found')
 
 ($index) = grep $hfile[$_] eq 'pre', 0 .. $#hfile;
 die 'No pre found' unless $index;
 
 I printed hfile using
   foreach (@hfile) { print $_\n; }
 
 and it looks fine! That is, there is a line with only pre on it!!!

Perhaps the line containing ‘pre’ contains whitespace characters that you 
cannot see when you print it. If so, you can replace you exact test with a 
regular expression:

  if( grep /pre/ @hfile ) {
…
  }

Or maybe pre occurs on the first line, in which case $index will have the 
value 0, which is treated as false, and your program will die.

This is all speculation because you have not provided us with your exact 
program and data files.


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




Re: Date::Parse and strange dates

2014-07-25 Thread Jim Gibson

On Jul 25, 2014, at 9:54 AM, Chris Knipe wrote:

 Hi All,
  
 I have the odd (very rare) case where I am given a date in an incorrect 
 format.  I already use Date::Parse to convert the dates to a unix timestamp, 
 and it’s working incredibly well.  However, on the rare case that I get 
 incorrect dates, Date::Parse does not like them either and errors out.  The 
 formats in question that I can’t parse basically looks like
  
 Thu, 23 Oct 2008 12:06:48+0400
  
 Note the lack of a space between the seconds and the timezone.
  
 Is there a simple quick way to fix that by means of a regex?

The simplest way to fix that particular error might be this regex:

  s/(\d)([+-])/$1 $2/



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




Re: List::MoreUtils with array of arrays not working

2014-07-10 Thread Jim Gibson

On Jul 10, 2014, at 11:50 AM, Natxo Asenjo wrote:

 On Thu, Jul 10, 2014 at 1:00 AM, Jim Gibson jimsgib...@gmail.com wrote:
 
 On Jul 9, 2014, at 2:58 PM, Natxo Asenjo wrote:
  On Wed, Jul 9, 2014 at 10:35 PM, Jim Gibson jimsgib...@gmail.com wrote:
  On Jul 9, 2014, at 1:20 PM, Natxo Asenjo wrote:
  
 In order to use the hash method of determining uniqueness, you must convert 
 your list values to a scalar value based on the content of the lists, not the 
 location or identity of the lists as by using the references to the list.
 
 The easiest way to do this is to join the elements of the list into a single 
 string. You need to separate the elements using a character that can not 
 appear in any of the elements of any list.
 
 For example, if the ':' character does not appear in any element, you can do 
 this:
 
   for my $listref ( @$seen_ref ) {
 my $key = join(':',@$listref);
 $hash{$key}++;
   }
 
 The keys of %hash will then represent the unique lists.
 
 yes! This is exactly it!.  Perfect.
 
 Just another question for the icing on the cake. When using the ++ on the 
 $hash{$key}++ how do I get the number of times every list was seen? My 
 apologies for not seeing the obvious here.

Iterate over the hash and print out the keys and the values (see below).

  
 It helps a lot if you post a complete, short program that illustrates the 
 problem you are having.
 
 yes, maybe I should have posted a link to a pastebin service. The problem in 
 this was that there was no small (less than 100 lines) short program because 
 the data from which the AoA gets created in the first place is coming from a 
 largish _DATA_ piece of text - and that is already trimmed to get a 
 representative piece of the real data.

You should just include the program in your message. If it is too long to 
include, it is probably too long for anybody to look at.

Here is a short, self-contained program that illustrates the technique:


#!/usr/bin/perl
use strict;
use warnings;
my $seen_ref = [ [qw(a b c d)], [qw( a b c d)], [qw(e f g g)] ];
my %hash;
for my $listref ( @$seen_ref ) { 
  my $key = join(':',@$listref);
  $hash{$key}++;
}
print Unique lists:\n;
for my $key ( keys %hash ) {
  printf %3d  %s\n, $hash{$key}, $key;
}


13 lines!


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




Re: List::MoreUtils with array of arrays not working

2014-07-09 Thread Jim Gibson

On Jul 9, 2014, at 1:20 PM, Natxo Asenjo wrote:

 hi,
 
 i have an array of arrays which contains equal elements. I would like to 
 isolate the unique values.

Do you mean that the subarrays contain equal NUMBERS of elements?

 
 I have tried using the uniq method of  List::MoreUtils but it apparently does 
 not work with an AoA.

That is true. List::MoreUtils::uniq expects a list of scalars (actually, all 
lists are lists of scalars). The function cannot figure out that the scalars in 
the list you have passed to it are actually references to other lists.


 This is what I tried:
 
 for my $i ( @$data_ref ) {
 push $seen_ref, [ $i-{'value1'}, $i-{'value2'}, $i-{'value3'}, 
 $i-{'value4'}, ];
 }
 
 my @unique = uniq $seen_ref;
 
 But unfortunately it does not work.
 
 How could I achieve this?



If you want to find out the unique values in any collection, insert those 
values as keys in a hash. Since keys in a hash are unique, when you are done 
inserting, the keys of the hash will be the unique values from your collection.

It doesn't matter what values you insert in the hash to go along with your 
keys. You are only interested in the keys. However, one common method would be 
to increment the hash value each time you insert a key. That way, when you are 
done, you will have a count of the number of times each value appears in your 
original collection:

  $hash{$key}++;

where $key takes on each of the values in your original collection.

Try to implement that scheme, and post your code here if you have any problems.


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




Re: List::MoreUtils with array of arrays not working

2014-07-09 Thread Jim Gibson

On Jul 9, 2014, at 2:58 PM, Natxo Asenjo wrote:

 
 
 
 On Wed, Jul 9, 2014 at 10:35 PM, Jim Gibson jimsgib...@gmail.com wrote:
 
 On Jul 9, 2014, at 1:20 PM, Natxo Asenjo wrote:
 
  hi,
 
  i have an array of arrays which contains equal elements. I would like to 
  isolate the unique values.
 
 Do you mean that the subarrays contain equal NUMBERS of elements? 
 
 yes, same number of elements but some subarrays are exactly the same as well.
 
 like this:
 
 $VAR1 = [
   [
 'a',
 'b',
 'c',
 'd'
   ],
   [
 'a',
 'b',
 'c',
 'd'
   ],
   [
 'e',
 'f',
 'g',
 'g'
   ]
   ];

So is that 7 unique values (a,b,c,d,e,f,g) or 2 unique values ( (a,b,c,d), 
(e,f,g,g) )?


  my %uniq;
 
 for my $i ( @$seen_ref ) {
 $uniq{$i} = ();
 }

If $seen_ref is a reference to an array of arrays, then the elements of 
@$seen_ref are references to arrays. By using those as keys, you are comparing 
references and not list elements.

In order to use the hash method of determining uniqueness, you must convert 
your list values to a scalar value based on the content of the lists, not the 
location or identity of the lists as by using the references to the list.

The easiest way to do this is to join the elements of the list into a single 
string. You need to separate the elements using a character that can not appear 
in any of the elements of any list.

For example, if the ':' character does not appear in any element, you can do 
this:

  for my $listref ( @$seen_ref ) { 
my $key = join(':',@$listref);
$hash{$key}++;
  }

The keys of %hash will then represent the unique lists.

It helps a lot if you post a complete, short program that illustrates the 
problem you are having.


--
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-07-01 Thread Jim Gibson

On Jul 1, 2014, at 1:26 AM, Uday Vernekar vernekaru...@gmail.com wrote:

 The script works fine without 
 next if $line =~ /^-/;
 
 How it helps.

It skips the line containing all dashes which separate the data lines. The 
script works without it because that line will fail the next test: ‘next unless 
scalar @f == 8’. However, checking the line for a single dash character at the 
beginning will be faster than trying to split the line with a regular 
expression and testing the number of fields that result. If you are only 
looking at a small number of lines, it probably doesn’t matter. In a large 
number of larger files, it might.

In general, when trying to parse complex files, it is best to identify and 
eliminate unwanted lines before trying to extract data from those that are 
relevant. Not doing so can lead to unwanted errors or program crashes in the 
future.


 On Mon, Jun 30, 2014 at 9:06 PM, Jim Gibson jimsgib...@gmail.com wrote:
 
 On Jun 30, 2014, at 2:44 AM, Uday Vernekar vernekaru...@gmail.com wrote:
 
  please Explain
 
  next if $line =~ /^-/;
 
 “Skip this input line if it starts with a dash ‘-‘ character.”
 
my @f = split('\s*\|\s*',$line);
 
 Break the input line into files separated by the vertical pipe character ‘|’ 
 and any whitespace before or after the pipe character, i.e., don’t include 
 the whitespace in the extracted fields.
 
next unless scalar @f == 8;
 
 “Skip this input line unless it consists of exactly 8 fields.”


--
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-30 Thread Jim Gibson

On Jun 30, 2014, at 2:44 AM, Uday Vernekar vernekaru...@gmail.com wrote:

 please Explain
 
 next if $line =~ /^-/;

“Skip this input line if it starts with a dash ‘-‘ character.”

   my @f = split('\s*\|\s*',$line);

Break the input line into files separated by the vertical pipe character ‘|’ 
and any whitespace before or after the pipe character, i.e., don’t include the 
whitespace in the extracted fields.

   next unless scalar @f == 8;

“Skip this input line unless it consists of exactly 8 fields.”


--
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 Jim Gibson

On 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;

Try this:

$c = () = $line =~ /\b$w\b/g;



--
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 Jim Gibson

On Jun 30, 2014, at 12:17 PM, Sunita Pradhan wrote:

 Thanks Jim. It is working but why a array is required here? 
 

Please respond to the list and not to me personally. That way, everybody will 
see your question, and somebody else can answer.

  
  Try this:
  
  $c = () = $line =~ /\b$w\b/g;

The empty array is necessary to put the return value of the binding operator 
'=~' into list context. Without it, the return value is in scalar context and 
returns just a 1 ('true'). In list context, the binding operator returns a list 
of the matched strings. When that is converted to scalar context by the 
assignment to $c, it becomes the size of the list.

See 'perldoc perlop', search for Regexp Quote-Like Operators, and scroll down 
to the section titled 'Matching is list context'.


--
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-26 Thread Jim Gibson

On Jun 26, 2014, at 2:05 AM, Uday Vernekar wrote:

 Please suggest if any Corrections Needed.

There are several improvements you could make.

 
 [code]
 #!/usr/bin/perl
 
 use 5.10.0;
 use strict;
 use warnings;
 #Pattern
 #U/A/S|Test|Test   |Loop | Run |Pass |Fail |  Arguments
 # | #  |Name   |Count|Count|Count|Count|
 #-++---+-+-+-+-+---
 # |  72| Traffic Test  |1|  561|  560|1| (none)
   

 my $pattern;

$pattern is not a good variable name for holding a string that matches some 
pattern. The 'pattern' is embedded in your regular expression. I would use 
something like $match or $found.

 open (my $Log_file, '', '/tmp/EO-PCPE-23-10GT') || die Couldn't open 
 /tmp/EO-PCPE-23-10GT\n\t $!;

When posting programs to a mailing list, you can use the special DATA file 
handle and put the lines at the end of your program after a line containing 
just a '__DATA__' marker. That way, people who do not have access to your data 
file will be able to run your program.

 while($Log_file)

It is usually better to use explicit variables:

  while( my $line = $Log_file ) {
if( $line =~ ... ) {

 {
 
 if($_ =~ 
 m/^(.+?)\|(.+72)\|(.+?)\|(.+?)\|(.+[0-9]|[0-9]|[0-9])\|(.+[0-9]|[0-9]|[0-9])\|(.+?)\|(.+?)$/)

This reqular expression is very long and hard to read. You seem to want match 
any line that:

1. Has seven '|' characters delimiting eight fields.
2. Has '72' in field 2.
3. Has numbers in fields 5 and 6.

I would recommend first splitting the line, then checking the individual fields 
for their desired content.

In addition, the regex fragment '(.+[0-9]|[0-9]|[0-9])' may not be doing what 
you think. This fragment will match:

1. At least one character followed by a digit (0-9) OR
2. A digit (0-9) OR
3. A digit (0-9)

The | character is alternation. You seem to be treating it as concatenation. 
The second and third alternatives are identical, and the third one is redundant.

If you want to match three successive digits, these will all work:

[0-9][0-9][0-9]
[0-9]{3}
\d\d\d
\d{3}


 {
  $pattern=$_;
 
 
 }
 
 }
 print Pattern Found:\n$pattern;
 my $uas=(split /\|/, $pattern)[0];
 $uas =~ s/^\s+//;
 my $test=(split /\|/, $pattern)[1];
 $test =~ s/^\s+//;
 my $test_name=(split /\|/, $pattern)[2];
 $test_name =~ s/^\s+//;
 my $loop_count=(split /\|/, $pattern)[3];
 $loop_count =~ s/^\s+//;
 my $run_count=(split /\|/, $pattern)[4];
 $run_count =~ s/^\s+//;
 my $pass_count=(split /\|/, $pattern)[5];
 $pass_count =~ s/^\s+//;
 my $fail_count=(split /\|/, $pattern)[6];
 $fail_count =~ s/^\s+//;
 my $arguments=(split /\|/, $pattern)[7];
 $arguments =~ s/^\s+//;

You can perform the split only once. You can also include optional whitespace 
in the delimiter string, which means the saved substrings will not include the 
whitespace:

  my( $uas, $test, $test_name, $loop_count, $run_count, $pass_count, 
$fail_count,
$arguments ) = split('\s*\|\s*',$line);

 print '-' x 30, \n;
 print   Test Data   \n;
 print '-' x 30, \n;
 print UAS : $uas\n;
 print Test : $test\n;
 print Test Name : $test_name\n;
 print Loop Count : $loop_count\n;
 print Run Count : $run_count\n;
 print Pass Count : $pass_count\n;
 print Fail Count : $fail_count\n;
 print Arguments : $arguments\n;
 print '-' x 30, \n;
 print   RESULTS   \n;
 print '-' x 30, \n;

You can use a 'HERE' document to print these lines:

print EOS;
--
  Test Data   
--
UAS : $uas
Test : $test
Test Name : $test_name
Loop Count : $loop_count
Run Count : $run_count
Pass Count : $pass_count
Fail Count : $fail_count
Arguments : $arguments
--
  RESULTS   
--
EOS


So putting that altogether, here is an improved program:

[code]

#!/usr/bin/env perl
use strict;
use warnings;
while( my $line = DATA ) {
  chomp($line);
  next if $line =~ /^-/;
  my @f = split('\s*\|\s*',$line);
  next unless scalar @f == 8;
  my( $uas, $test, $test_name, $loop_count, $run_count, $pass_count, 
$fail_count,
$arguments ) = @f;
  if( $test eq '72' ) {
print EOS;
--
  Test Data   
--
UAS : $uas
Test : $test
Test Name : $test_name
Loop Count : $loop_count
Run Count : $run_count
Pass Count : $pass_count
Fail Count : $fail_count
Arguments : $arguments
--
  RESULTS   
--
EOS
if( $fail_count != 0  $run_count = 0 ) {
  print Result: Fail\n;
}elsif( $fail_count == 0  $run_count  0 ) {
  print Result: Pass\n;
}
  }
}
__DATA__
U/A/S|Test|Test   |Loop | Run |Pass |Fail |  Arguments
 | #  |Name   

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

2014-06-25 Thread Jim Gibson

On Jun 25, 2014, at 12:11 AM, Uday Vernekar vernekaru...@gmail.com wrote:

 Dear Ron,

You are better off addressing your questions to the entire mailing list, rather 
than asking information from one person. Ron is not obligated to help you and 
may not be available, but others may be willing to help you.

 How wud i grep the string  |  72| Traffic Test  |1|  561| 
 from log file which is Very large.

You would: 

1. open the file for reading
2. read each line in the file
3. check each line for your desired pattern

That is what grep does. By doing this in Perl, you save having to create 
another process. You can combine the step of finding the pattern and extracting 
information from the desired line. You can also quit after you have found the 
line you are seeking, if you only need to find one match; grep will continue to 
read the rest of the file looking for more matches.

Let us know if you have problems with any of these steps.


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




Re: bash to perl for cgi

2014-06-17 Thread Jim Gibson

On Jun 17, 2014, at 1:10 AM, Philippe Rousselot rousse...@rousselot.org wrote:

 Hi, 
 
 I know nothing about perl and I have a problem with a cgi script for a 
 website called geneweb (genealogy stuff). 
 
 I moved from one web site to another and now the site does not work and give 
 me a 500 error message. 

Do you have access to the web server logs? Those could be very helpful in 
diagnosing your error.

 the script I need to call the program is the following 
 
 ~~ 
#!/bin/sh 
 DIR=/homez.xxx//www/geneweb607/gw 
 cd $DIR 
 $DIR/gwd -cgi 2/dev/null 
 
 ~~ 
 
 I guessed, but I may be wrong that I cannot use a sh script (I checked for 
 files and folders rights) 

I am no web expert, but as far as I know, there is no reason why you can’t run 
a shell script as a CGI program. However, there may be security issues, and you 
may have reconfigure your server. You are probably better off using Perl 
instead.
  
 Could someone give me a translation in perl of this script so I can try out 
 this idea 

Here is a Perl program that does the same thing as your shell script:

#!/bin/env perl
use strict;
use warnings;
my $dir = q(/homez.xxx//www/geneweb607/gw);
system(“cd $dir;$dir/gwd -cgi 2/dev/null”)’

Good luck!


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




Re: Stopping undefined warnings

2014-06-17 Thread Jim Gibson

On Jun 17, 2014, at 1:02 PM, SSC_perl wrote:

   What's the best way to stop undefined warnings for code like this:
 
 $data-{'image'} = CopyTempFile('image') if ($main::global-{'admin'}  
 $main::global-{'form'}-{'image_upload'} ne '');
 
   CGI::Carp gives the following:
 
 [Tue Jun 17 14:54:36 2014] admin.cgi: Use of uninitialized value in string ne 
 at admin.cgi line 219.
 
   I know that I can surround the section with 
 { 
 no warnings 'uninitialized';
 ...
 }
 
 or I could add a check for defined-ness as follows:
 
 $data-{'image'} = CopyTempFile('image') if ($main::global-{'admin'}  
 defined $main::global-{'form'}-{'image_upload'}  
 $main::global-{'form'}-{'image_upload'} ne '');
 
   Is there a better way to stop this warning in situations like this?  
 I'd like to keep these warnings from filling up the log.

Best and better are subjective terms about which people will argue.

Me, I would split your one, long line into several lines and use a temporary 
variable to hold the possibly undefined value and assigning '' to it if it is 
undefined:


  my $upload = $main::global-{'form'}-{'image_upload'} || '';
  if ($main::global-{'admin'}  $upload ne '' ) {
$data-{'image'} = CopyTempFile('image');
  }


I find that much more readable and will not generate any undefined warnings.

Note that later Perls can use the // operator in the first line to test the 
definedness of the hash value:

  my $upload = $main::global-{'form'}-{'image_upload'} // '';


but there is no practical instance in this case. There would be if you needed 
to distinguish zero or '' from undef.


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




Re: how to create a text progress status line that updates on the same line in Perl?

2014-06-10 Thread Jim Gibson

On Jun 10, 2014, at 2:59 PM, Kenneth Wolcott wrote:

 Hi All;
 
 how to create a text progress status line that updates on the same line in 
 Perl?
 
 I know that this questions is probably not well-posed, but I hope you
 get what I'm after.
 
 I'd like to do what application installers do, describing the status,
 updating the status occasionally, but on the same line overwriting
 what was there earlier.
 
 Do I need to use the hex or oct form of the backspace (octal 010) for
 each character that I want to overwrite?

Quick answer:

1. Use print (not say),
2. Turn on autoflushing ($|++),
3. Put a carriage return character (\r) at the beginning of the line,
4. Don't put a new line (\n) at the end of the line, and 
5. Either use the same, fixed number of characters each time or add spaces at 
the end of short lines to erase any characters left over from a previous line.

Check this out:

perl -e '$|++;for (0..20) { $x=q(=)x$_;$y=q( )x(20-$_); print 
qq(\r$x$y);sleep(1);}' 
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Brackets in scalar and array

2014-05-29 Thread Jim Gibson

On May 29, 2014, at 1:20 PM, James Kerwin wrote:

 Hello all, long time lurker, first time requester...
 
 I have a Perl exam tomorrow and came across a question that I just cannot 
 find an answer to (past paper, this isn't cheating or homework etc.).
 
 Explain the difference between:
 
 ($test)=(@test);
 
 And
 
 $test=@test;
 
 If anybody could shed any light on this I'd be very grateful.

The difference is the context of the assignment: scalar or list, and how 
@test (or (@test)) is evaluated in that context.

In the first statement ($test) = (@test), the parentheses around $test in the 
left-hand side (LHS) of the assignment places the evaluation of the right-hand 
side (RHS) in list context. In list context, with two lists on either side of 
the assignment operator (=), assignment is made from each element on the RHS to 
the corresponding element on the LHS. Therefore, the one and only element on 
the LHS ($test) gets assigned the value of the first element of the RHS, and 
$test ends up with the value of $test[0].

In the second statement, the assignment is done in scalar context, and the RHS 
is evaluated in scalar context. A list evaluated in scalar context returns the 
number of elements in the list, and $test is assigned the value ($#test+1).

Note that the parentheses around @test in the first statement are irrelevant. 
The context is list with or without them.

Try it yourself:

% perl -e '@t=qw(1 2 3);$t=@t;print qq($t\n);'
3
% perl -e '@t=qw(1 2 3);($t)=@t;print qq($t\n);'
1
% perl -e '@t=qw(1 2 3);($t)=(@t);print qq($t\n);'
1
 



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




Re: Brackets in scalar and array

2014-05-29 Thread Jim Gibson

On May 29, 2014, at 3:34 PM, Sherman Willden wrote:

 Maybe I'm missing the point but isn't the following code the problem's 
 answer? Please let me know if I am off base.

Just a bit off (see below).

 #!/usr/bin/perl
 
 my @test = a b c;

That is a scalar on the right-hand side. You end up with a one-element array in 
which the first and only element is the string 'a b c'. Shawn and I were using 
the qw() operator, which splits a string on whitespace and returns a list:

  my @test = qw(a b c);

which is equivalent to and shorter than:

  my @test = ( 'a', 'b', 'c');



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




Re: How to implement locks/gates/semaphores to alleviate race conditions?

2014-05-24 Thread Jim Gibson

On May 24, 2014, at 9:40 AM, siegfr...@heintze.com wrote:

 
 I have multiple processes running cygwin/bash that are accessing the same 
 files in a certain directory.
 I want to create a lock or semaphore or gate to serialize access to this 
 directory so that no two (or more processes) can access the directory at any 
 one time. As soon as the first process running bash grabs the lock using 
 perl, the perl program exits, bash creates a file, and bash then needs to 
 call a second perl program to release the lock or event so that only one of 
 the other blocking processes can now grab the lock.
 
 Can someone recommend a way to do this in perl or python? How would I do 
 this? I can think of several ways and they all sound difficult
 (1) Create a memory resident Win32 Event. This is tedious because the lock 
 will be released when the perl program exists. I need to keep the lock until 
 bash executes a second perl program. I suppose bash could call perl as a 
 child process which would then grab the Win32 event and wait on a socket or a 
 second win32 event until the parent bash program is ready to release the 
 first win32 Event. This sounds much to complicated (and OS specific). Please 
 tell me there is an easier way!
 
 (2) I could use the resource manager built into SQL Server. I don't know how 
 to do this from perl. Is it possible? I don't like this option because it not 
 only requires SQL Server be installed and running but only works on windows.
 
 (3) Is there a way to do it with the Microsoft Access database? While this 
 has the advantage of not requiring a server be running (like SQL Server), it 
 is not OS neutral (and I don't know how to do it).
 
 (4) Perhaps there is cygwin implementation of Unix style semaphore that I can 
 call from perl? Are there any packages for this? This still has the problems 
 of option #1.
 
 (5) Gollly! I don't like any of the above options! They are all so 
 complicated. Is there something simpler? 

I would try creating a “lock” file in the directory. File creation is pretty 
fast. You can use the file creation or modification time to recover from a 
stuck lock if you know about how long a lock should be held.
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Append new line at end of non-quoted text

2014-05-23 Thread Jim Gibson

On May 23, 2014, at 2:45 PM, Sherman Willden wrote:

 Disclaimer: I am 67 and not in school. I am doing this for my own 
 satisfaction.
 
 How do I get a new line at the end of a non-quoted text. I am doing the 
 following:
 Use Math::Trig;
 print pi * 2;
 print \n;
 
 How do I get the new line on the same line of code?
 
 I could do my $my_pi_times_two = pi * 2;
 print $my_pi_times_two\n;
 
 but that seems to be overkill.


There are several ways.

1. You can use the new 'say' function, instead of 'print', which automatically 
adds a newline to every output. Put 'use feature say' at the beginning of your 
program:

   say pi * 2;

2. You can print a list:

print pi * 2, \n;

3. You can concatenate a newline onto the end of your string:

print pi * 2 . \n;

4. You can use the printf function:

printf %f\n, pi * 2


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




Re: Append new line at end of non-quoted text

2014-05-23 Thread Jim Gibson
Please post messages to the list, not to me personally. That way, you will get 
better answers sooner.

On May 23, 2014, at 3:13 PM, Sherman Willden wrote:

 Thank you, Jim;
 
 How do I get rid of the warning message without getting rid of the -w switch?

Use the 'use warnings;' pragma in your program instead of '-w' on the first 
line. That way, you can control which messages are issued.

I do not know if it is possible to get rid of the warnings you are seeing. I do 
not use the 'say' command, but prefer print, and use one of the other 
techniques I listed.

See 'perldoc use warnings' and 'perldoc perllexwarn' for more details about 
'use warnings'.


 The code is last in this text. The output is as follows:
 
 perl -c nums.pl
 Unquoted string say may clash with future reserved word at nums.pl line 4.
 nums.pl syntax OK
 
 perl nums.pl
 Unquoted string say may clash with future reserved word at nums.pl line 4.
 6.28318530717959
 6.28318530717959
 6.28318530717959
 6.283185
 
 #!/usr/bin/perl -w
 
 use Math::Trig;
 use feature say;
 
 say pi * 2;
 print pi * 2, \n;
 print pi * 2 . \n;
 printf %f\n, pi * 2;
 


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




Re: How to parse C#, javascript, lisp source code for quoted literal strings

2014-05-22 Thread Jim Gibson

On May 22, 2014, at 2:04 AM, siegfr...@heintze.com siegfr...@heintze.com 
wrote:

 I need to extract some information from source code.
 
 How can I write a perl regular expression that will match a literal string in 
 languages like C#, javascript, java and lisp?
 
 Here is my naive approach:
 
 /[^]*/
 
 This of course does not accommodate backslashes in the string that perl, C, 
 C# javascript use.
 
 \sdfds\\\r\\t\\m.
 
 How can I write a regular expression in perl to look for a double quoted 
 literal string in these languages?


The Regexp::Common module, available from cpan.org, has several useful 
categories of regular expressions. Among these is Regexp::Common::delimited for 
finding delimited strings, which you may find useful.



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




Re: find specific line from file

2014-05-20 Thread Jim Gibson

On May 20, 2014, at 4:19 PM, Benjamin Fernandis wrote:

 Hi,
 
 I want to fetch rawuuid from below file for each partition name.
 
 I tried to use while loop and all but no luck.
 
  example : partition name : ada0p2 
 rawuuid: 5899824d-e019-11e3-9cbc-08002731cc9a
 file :
 
  Geom name: ada0

This seem like a simple job for a couple of regular expressions. How did you go 
about extracting the partition name and rawuuid value? Please post your code in 
your next message so we can give you some helpful suggestions.


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




Re: CPAN unavailable

2014-05-20 Thread Jim Gibson

On May 20, 2014, at 6:41 PM, Yonghua Peng sys...@mail2000.us wrote:

 I probably meant search.cpan.org doesn't work.

Try picking a different mirror. These are the ones I am using:

http://httpupdate35.cpanel.net/CPAN/
http://mirrors.gossamer-threads.com/CPAN/
http://cpan.cs.utah.edu/


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




Re: find specific line from file

2014-05-20 Thread Jim Gibson
Benjamin:

Please post messages to the list, not individual members.


On May 20, 2014, at 6:51 PM, Benjamin Fernandis benjo11...@gmail.com wrote:

 Hey Jim,
 
 I tried to use while loop to read file line by line, but facing problem to 
 get exact phrase or a way to start reading from predefined partition name and 
 then fetch next coming rawuuid.
 
 Thanks
 Ben

I would:

1. Read the file line-by-line.
2. Look for partition name and save in a variable
3. Look for rawuuid name and combine with previously saved partition name.
4. Repeat until no more lines to read.
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




  1   2   3   4   5   6   7   8   >