Re: testing for a file type

2007-12-18 Thread Ankur Gupta
On Dec 18, 2007 10:08 PM, goldtech [EMAIL PROTECTED] wrote:

 Hi,

 If I have:

 ...
 foreach (@ARGV) {
print do something only to .mdb files;
 }

 I could use File::Basename's fileparse and test for the file extension
 and put a big if statement around or in the foreach loop. So if a user
 puts a non .mdb file argument on the cmd line it won't process and
 prints a usage.

 But I suspect in perl theres a more compact way of doing that?

I don't think you need to use File::Basename.

You can simply do this.

foreach my $file (@ARGV) {
if ( $file !~ /\.mdb$/ ) {
print $file is not a mdb file. Ignoring...\n;
next;
}

# code to pocess .mdb file
...
...
}

-- 
Ankur

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




Re: Downloadable and Online Perl Documentation

2007-12-18 Thread Ankur Gupta
On Dec 19, 2007 2:40 AM,  [EMAIL PROTECTED] wrote:
 Hello

 i am looking for perl documenation that would aid in the determining what 
 code to write and how to determine how one made a syntax error and also 
 available functions.

 I need the documentation 2 formats. The first would be something that can be 
 retrieved online for when I am online ( a link to the documentation). The 
 second will be something i can download.  will be gone for a week and working 
 on a few scripts. However, I will not be able to look up information online 
 so I need something that can be read from disk in perhaps pdf format.

If you have a unix/linux box then no need to download/install any manual.
Just type perldoc perl to get started.

But if you want to go online or view the documentation in a web browser,
then I think http://perldoc.perl.org is the best.

You can also download it for off line viewing(has both html and pdf formats).

http://perldoc.perl.org/perldoc.tar.gz

-- 
Ankur

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




Better way to add one line at top of every file(one liner)

2006-05-18 Thread Ankur Gupta

perl -0777 -p -i -e 'print abcdefgh\n' *.ext
or
perl -0777 -p -i -e 's#^#abcdefgh\n#'  *.ext
or
???

--Ankur

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




Tie::File adds extra lines if recsep is \n\n

2006-05-10 Thread Ankur Gupta

Hi,

Using Tie::File with recsep = \n\n adds two extra lines to the
original file when I iterate through the entire file. If I just change
one record then its fine.

Below is the program

use strict;
use warnings;

use Tie::File;

my @array;
tie @array, 'Tie::File', 'file', recsep = \n\n or die $!;

foreach my $rec ( @array ){
   print $rec;
}

untie @array;

$- diff file file.orig
8464,8465d8463



Right now, I am tieing the file again without recsep and popping two records.

tie @array, 'Tie::File', 'file' or die $!;
pop(@array);
pop(@array);
untie @array;

This fixes the problem but is there a better way to get around this?

perl version is 5.8.0 and latest version of Tie::File (0.97).

Thanks,

--Ankur

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




Re: Tie::File adds extra lines if recsep is \n\n

2006-05-10 Thread Ankur Gupta

On 5/10/06, D. Bolliger [EMAIL PROTECTED] wrote:

Ankur Gupta am Mittwoch, 10. Mai 2006 11.23:
 Hi,

 Using Tie::File with recsep = \n\n adds two extra lines to the
 original file when I iterate through the entire file. If I just change
 one record then its fine.

 Below is the program

 use strict;
 use warnings;

 use Tie::File;

 my @array;
 tie @array, 'Tie::File', 'file', recsep = \n\n or die $!;

 foreach my $rec ( @array ){
 print $rec;
 }

 untie @array;

 $- diff file file.orig
 8464,8465d8463
 
 

 Right now, I am tieing the file again without recsep and popping two
 records.

 tie @array, 'Tie::File', 'file' or die $!;
 pop(@array);
 pop(@array);
 untie @array;

 This fixes the problem but is there a better way to get around this?

 perl version is 5.8.0 and latest version of Tie::File (0.97).

Hi Ankur Gupta

Your file stays unchanged only if it ends with recsep, \n\n in your case.
(So one workaround instead of the two pops would be to make sure the input
file contains this recsep at the end)


Thanks for letting me know. I didn't know this until you told me and I
tried it out. Now I can not use the pop*2 solution as it would have
deleted unnecessary lines if the record was ending with the recsep. I
can keep the file in the correct state by adding recsep at the end,
but the problem is that the file can be edited by anyone in my team
using the script or by hand. So I added the following before untie
pop(@array) if $array[-1] eq '';
So now this will not create any extra records even if the last record
does not end with recsep. It may add a new line which I am ok with.


This behaviour is described in perldoc Tie::File, but not enough prominent
imo (and done by _fixrecs()).


I should have read the document clearly and completely. It does say abt it.
[...]
There is no way to create a file whose trailing record separator
string is missing
[...]


   I think not all people expect the tied file to be altered when no write
access is done. In Ankur Gupta's example, records are even added with every
(un)tie.


That is true. If I am not altering any record, I want it to be unchanged.


I'm not sure if this is a bug. Should the file stay unaltered if it's never
accessed for writing? Should the last record even be treated specially?


Can't it make an exception for the last record?
If it can't be fixed, can it be added to the CAVEATS section.
And would be great if a workaround is suggested.

Anyway, I like this module and will be using it as it provides a nice
abstraction in dealing with files.

--Ankur

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




RE: deleting an element from an array

2006-04-22 Thread Ankur Gupta
Johan Meskens CS3 jmcs3
mailto:[EMAIL PROTECTED] scribbled on
Saturday, April 22, 2006 5:26 PM:

 hello 
 i want to delete an element from an anonymous array in a hash with:
 
 delete ${$alltheworlds{ $d }}[$num];

perldoc -f splice.

my $deleted_element = splice(@{$alltheworlds{ $d }} , $num, 1); 

should do the trick.

 now instead of being being deleted it turns out be 'undef'
 
 and
 my @array = ( undef, one, two );
 print scalar @array gives :3

undef is a legal value for an array element.

 so the element is only half deleted

I do not think there is such thing as half deleted. 
Its either deleted or not deleted.

--Ankur

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




Class::DBI is slow?

2006-04-20 Thread Ankur Gupta
Hi All,

My first try with Class::DBI and DBI modules and I find that making a
query using Class::DBI takes much much more time than compared to DBI.

Is it me who is doing something wrong or Class::DBI is always slower(I
have kind of feeling that its me who is doing something wrong).

Also, I have another question. 
Why do I need to specify the column names, primary keys in Class::DBI
while not in DBI?

BTW, I have ~40k records and using mysql 5.0. 

*** using DBI ***

use strict;
use warnings;
use DBI();

my $dbh =
DBI-connect(DBI:mysql:database=scratch;host=blah,user,passwd);

my $sth = $dbh-prepare(SELECT field from table where user = 'user1');
$sth-execute();
while (my $ref = $sth-fetchrow_hashref()) {
print $ref-{field}, \n;
}
$sth-finish();
$dbh-disconnect();

## Returns the result in a flash

*** using Class::DBI ***

use strict;
use warnings;

use Test::Personal;
my @users = Test::Personal-search(user = user1);

foreach my $u ( @users ){
print $u-field, \n;
}

## Returns the result very slowly.

Test::Personal

package Test::Personal;
use base 'Test::DBI';

Test::Personal-table('table');
Test::Personal-columns(Primary = qw/user start_time/);
Test::Personal-columns(Others = qw/field/);

1;

_Test::DBI___

package Test::DBI;
use base 'Class::DBI';

Test::DBI-connection('dbi:mysql:database=scratch;host=blah', 'user',
'password');

1;

--Ankur

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




RE: golf

2006-04-19 Thread Ankur Gupta
Chad Perrin mailto:[EMAIL PROTECTED] scribbled on Wednesday, April
19, 2006 6:59 PM:

 On Wed, Apr 19, 2006 at 06:51:21PM -0700, Timothy Johnson wrote:
 
 You mean like this?
 
 perl -p -e s/\n/ /
 
 Thanks.  I looked -p up in perlrun and learned something new.  It's
 not quite what I set out to learn, but learning new things is good
 anyway.  
 
 I was actually looking for something doable in a file with a shebang
 line and the executable bit set. 

{
local $/ = undef;
while () {
s/\n/ /sg;
print;
}
}

--Ankur

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




RE: array help

2006-04-13 Thread Ankur Gupta
Irfan J Sayed mailto:[EMAIL PROTECTED] scribbled on Thursday, April
13, 2006 9:46 AM:

 Hi,
 
 I am executing following command.
 
 my @activity = system cleartool lsactivity -short -view
 Admin_Irfan_Project_int; 
 
 but the output of this command is not storing in the array. array is
 empty. 

This is what people generally do if their perl program is not doing what
they want.

1. print output of @activity hmmm. its some number... why number..
Let me look me in the manual of system command for the possible values
it returns.

So I do perldoc -f system (or google if I wish).

[...]

The return value is the exit status of the program as
returned by the Cwait() call. 

[...]

oh.. so this is not the function I want. 

If you read further, you will see 

[...]

This is INOT what you want to use to capture
the output from a command, for that you should use merely backticks or
Cqx//, as described in Lperlop/`STRING`.

[...]

Eurika, I found the answer. 

Use either qx// or ``. 

I do perldoc perlop read the section under qx// and `STRING`.

Change the line to 
@activity = `cleartool lsactivity -short -view Admin_Irfan_Project_int`;

Its now working. 
Enough work for today. Have a cup of coffee.

--Ankur

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




RE: Perl regular exp

2006-04-11 Thread Ankur Gupta
Sonika Sachdeva mailto:[EMAIL PROTECTED] scribbled on Tuesday,
April 11, 2006 3:39 PM:

 Hi ,

Please state your problem statement. 
What are you trying to achieve with this program.

add 

use strict;
use warnings; 

at the top of your perl program and then try to run.
 
 print $line if ($line =~ /pattern1  pattern2  pattern3/);

did you mean pattern1 or $pattern1.

 works .. but
 
 my $regex=$pattern1  $pattern2   $pattern3; print $line if
 ($line =~ /$regex/); 

did you mean pattern1 or $pattern1.

 doesn't work...

What does $pattern1, $pattern and $pattern store.

And please, BOTTOM POST.

And atleast read perldoc perlintro.. 

--Ankur

perl -e '[EMAIL PROTECTED]/(^\+_'
Warning: Use of comic-book profanity not allowed.

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




RE: Perl regular exp

2006-04-11 Thread Ankur Gupta
Sonika Sachdeva mailto:[EMAIL PROTECTED] scribbled on Tuesday,
April 11, 2006 4:27 PM:

 Actually I am looking for AND and OR combinations..and the number of
 words are not fixed. 
 ie @words is the variable and I need to have OR and AND combinations
 of @words. to match in LINES How do I go about it? 

perldoc -f eval

eg.

use strict;
use warnings;

## number of @words can vary
my @words = qw/a b c d/;
## $condition can be ||, and, or. 
my $condition = '';

my $string = join  $condition , map { /$_/ } @words;
$string = 'print $_ if ' . $string;

# $string will have 'print $_ if /a/  /b/  /c/  /d/'
while (){
eval $string;
}

But make sure that @words and $condition are not input by user as then
it creates a security hole. 
Or if they are input by the user, then check for the values before you
create the eval string.

--Ankur

perl -e '[EMAIL PROTECTED]/(^\+_'
Warning: Use of comic-book profanity not allowed.

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




RE: Date difference.

2006-04-06 Thread Ankur Gupta
hridyesh pant mailto:[EMAIL PROTECTED] scribbled on Wednesday,
April 05, 2006 11:25 PM:

 Hi,
 i have two date string reading from the log file like below.
 $date1=Mon Mar 27 02:45:15 2006;
 $date2=Wed Apr  5 23:20:46 2006;
 
 $Number_of_Days = $date1-$date2;
 i want to get number of days between these two dates.
 Can someone help me.

Sure.
What did you try till now?

Anyway, 

perldoc -q 'How can I compare two dates and find the difference?'

-Ankur

$SIG{ALRM} = {
snooze;
sleep 300;
}

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




problem extracting data with WWW::Mechanize whe

2006-01-15 Thread Ankur Gupta
Hi,

I have a very simple WWW::Mechanize perl program which does the following task.
1. Gets the login URL.
2. Enters username and password.
3. Get another URL.
4. Fill some fields of date range and submit.
5. Parse the content and create a report.

It used to work until the web designer changed the form fields, added
some javascript and the program stopped working.

So I changed my program(basically the form fields), but I am unable to
get the *content* in #4. Infact the content is same as the content of
#3.

After googling, reading the docs, trying out things for hours, I am
unable to crack it :((.

Following are the form fields which I get from the program. Which
seems identical to the fields in the html source.
option: orderdaterangeinputstore:st : 14
option: orderdaterangeinputstore:star : 01
option: orderdaterangeinputstore:sta : 2006
option: orderdaterangeinputstore:end : 15
option: orderdaterangeinputstore:endm : 01
option: orderdaterangeinputstore:endy : 2006
submit: orderdaterangeinputstore:_id11 :
hidden: orderdaterangeinputstore:merchantID : 100106
hidden: orderdaterangeinputstore:statusID : 2109
hidden: jsf_tree_64 :  very_long_string_hash
hidden: jsf_state_64 : very_long_string_hash
hidden: jsf_viewid : /merchant/merchantDateRange.jsp
hidden: orderdaterangeinputstore_SUBMIT : 1
hidden: orderdaterangeinputstore:_link_hidden_ :

Following is the code and I have attached the html source of #3.

use strict;
use warnings;

use WWW::Mechanize;
my $mech = WWW::Mechanize-new();

my $url = login_url;
$mech-get($url);

$mech-set_fields(
'_id0:_id8' = 'user',
'_id0:_id12' = 'password'
);
$mech-click();

$mech-get('another_url');

$mech-set_fields(
'orderdaterangeinputstore:endy' = 2006,
'orderdaterangeinputstore:endm' = '01',
'orderdaterangeinputstore:end' = 15,
'orderdaterangeinputstore:sta' = 2006,
'orderdaterangeinputstore:star' = '01',
'orderdaterangeinputstore:st' = 14
);

$mech-click();
print $mech-content;

--Ankur

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


Re: problem extracting data with WWW::Mechanize whe

2006-01-15 Thread Ankur Gupta
On 1/15/06, Ankur Gupta [EMAIL PROTECTED] wrote:
 Hi,

 I have a very simple WWW::Mechanize perl program which does the following 
 task.
 1. Gets the login URL.
 2. Enters username and password.
 3. Get another URL.
 4. Fill some fields of date range and submit.
 5. Parse the content and create a report.

 It used to work until the web designer changed the form fields, added
 some javascript and the program stopped working.

 So I changed my program(basically the form fields), but I am unable to
 get the *content* in #4. Infact the content is same as the content of
 #3.

 After googling, reading the docs, trying out things for hours, I am
 unable to crack it :((.

 Following are the form fields which I get from the program. Which
 seems identical to the fields in the html source.
 option: orderdaterangeinputstore:st : 14
 option: orderdaterangeinputstore:star : 01
 option: orderdaterangeinputstore:sta : 2006
 option: orderdaterangeinputstore:end : 15
 option: orderdaterangeinputstore:endm : 01
 option: orderdaterangeinputstore:endy : 2006
 submit: orderdaterangeinputstore:_id11 :
 hidden: orderdaterangeinputstore:merchantID : 100106
 hidden: orderdaterangeinputstore:statusID : 2109
 hidden: jsf_tree_64 :  very_long_string_hash
 hidden: jsf_state_64 : very_long_string_hash
 hidden: jsf_viewid : /merchant/merchantDateRange.jsp
 hidden: orderdaterangeinputstore_SUBMIT : 1
 hidden: orderdaterangeinputstore:_link_hidden_ :

 Following is the code and I have attached the html source of #3.

 use strict;
 use warnings;

 use WWW::Mechanize;
 my $mech = WWW::Mechanize-new();

 my $url = login_url;
 $mech-get($url);

 $mech-set_fields(
 '_id0:_id8' = 'user',
 '_id0:_id12' = 'password'
 );
 $mech-click();

 $mech-get('another_url');

 $mech-set_fields(
 'orderdaterangeinputstore:endy' = 2006,
 'orderdaterangeinputstore:endm' = '01',
 'orderdaterangeinputstore:end' = 15,
 'orderdaterangeinputstore:sta' = 2006,
 'orderdaterangeinputstore:star' = '01',
 'orderdaterangeinputstore:st' = 14
 );

 $mech-click();
 print $mech-content;

I see the following javascript code in the login page

Login page..
input id=_id0:_id14 name=_id0:_id14 type=image
src=../images/submit.gif onclick=clear__5Fid0();/

[...]

!--
function clear__5Fid0() {
  var f = document.forms['_id0'];
  f.elements['_id0:_link_hidden_'].value=null;
  f.target='';
}
clear__5Fid0();
//--

---

DateRange Page

[...]

input id=orderdaterangeinputstore:_id11
name=orderdaterangeinputstore:_id11 type=submit
onclick=clear_orderdaterangeinputstore(); title=Submit/

[...]

!--
function clear_orderdaterangeinputstore() {
  var f = document.forms['orderdaterangeinputstore'];
  f.elements['orderdaterangeinputstore:_link_hidden_'].value=null;
  f.target='';
}
clear_orderdaterangeinputstore();
//--

---

What my question is whether there is any connection between
_link_hidden_ field between the login page and the other page.

I have tried setting _link_hidden_ field to undef/null value
before/after $mech-click is called but did not help.

Another question is whether $mech-click calls the javascript function
clear_orderdaterangeinputstore (onclick).

Thanks,

--Ankur

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




LWP: How to make sure login was successful

2006-01-09 Thread Ankur Gupta
I am writing a LWP program.
I need to login to 10 different sites and extract information out of them..
Each site has its own username/password.

I am writing a common module which will do the job of logging in.
I am doing all sorts of error catching such as whether internet is up
or not, the url is correct or not, etc. I also need to make sure the
login was successful.
But I am not sure how to do that. The status code returned is 200 OK
which is true.
The resulting page has the string Invalid login which I can grep for.
But 10 different sites would have differnt invalid login messages.

I want to know is there a better way to do the job?

Following is my login subroutine...

sub _login {
my ($ua, $user_field, $username, $password_field, $password,
$top_url, $login_page) = @_;

my $response;
$response = $ua-get($top_url/$login_page);
confess $top_url/$login_page: , $response-status_line unless
$response-is_success;
my ($form) = HTML::Form-parse($response);

$form-value($user_field, $username);
$form-value($password_field, $password);
my $req = $form-click;

## Get a response object
$response = $ua-request($req);

## If the response is good then get its content else print why and
what failed
confess $response-status_line unless $response-is_success;
print $response-status_line;
#print $response-content;
return $response-content;
}

Thanks,
--Ankur

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




Re: getting shell environment varibale in perl after sourcing a file

2005-09-25 Thread Ankur Gupta

On 9/24/2005 6:10 PM Manish Sapariya wrote:


Hi all,
I have some SHELL environment file which I need to get the variable from
and use it my perl script.

As I understand, the ENV hash will be populated using the environment of
the shell that I have executed the perl script from.

Is there any way for me to update the ENV hash by sourcing some other file
into my perl environment.

In summary I want equivalent or `source /root/.myrc` which will give me
all variable, the one which are overwritten by .myrc in my perl ENV hash.


perldoc Shell::Source

http://search.cpan.org/~pjcj/Shell-Source-0.01/Source.pm

HTH...

--
Ankur

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




Re: Looking for perl scripts to remove ^M

2005-09-23 Thread Ankur Gupta

On 9/23/2005 11:28 PM Dave Adams wrote:


Sometimes I get perl scripts that were developed on windows and then
brought over to UNIX and the scripts contain all the pesky
metacharacters of ^M and excessive blank lines.

Does anyone have a simple script to clean these files up or suggestions?


If you are using vi/vim as your editor then this is the good way to deal 
with it..


:%s/.$//

will remove the last *pesky* character(^M) from all lines

But as Chris said, did you try anything so far...

--
Ankur

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




Re: Hash of Arrays

2005-09-20 Thread Ankur Gupta

On 9/20/2005 11:16 PM Christopher Spears wrote:


I've been learning about data structures by reading
the Programming Perl book.  Here is a code snippet:

while ($line = ) {


# If $line = abcd: efgh: ijkl;


($who, $rest) = split /:\s*/, $line, 2;


# then $who = abcd and $rest = efgh: ijkl;


@fields = split ' ', $rest;
$HoA{$who} = [ @fields ];
}

The part that confuses me is:

($who, $rest) = split /:\s*/, $line, 2;

I understand that it takes the input and splits it
into two parts along the regular expression, but I
can't figure out what the 2 means.


perldoc -f split

split /PATTERN/,EXPR,LIMIT

[...]

If LIMIT is specified and positive, splits into no more than that
many fields (though it may split into fewer).  If LIMIT is unspecified
or zero, trailing null fields are stripped (which potential users
of Cpop() would do well to remember).  If LIMIT is negative, it is
treated as if an arbitrarily large LIMIT had been specified.

[...]

The LIMIT parameter can be used to split a line partially

($login, $passwd, $remainder) = split(/:/, $_, 3);

When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT
one larger than the number of variables in the list, to avoid
unnecessary work.  For the list above LIMIT would have been 4 by
default.  In time critical applications it behooves you not to split
into more fields than you really need.

[...]

--
Ankur

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




Re: hash question

2005-09-06 Thread Ankur Gupta

On 9/6/2005 4:50 PM Gergely Buday wrote:

Hi there, 


do you have a clue why is this not working? The interpreter complains
about a syntax error in line 7 near $myhash.


Seems like you are confused with the brackets...


#!/usr/bin/perl

%myhash = { alma = apple, korte = pear };


Should be

%myhash = ( alma = apple, korte = pear );


foreach $ky (keys (%myhash))


No need for any brackets around the hash

foreach $ky (keys %myhash)


{
print $ky, : , $myhash($ky), \n;


Should be

  print $ky, : , $myhash{$ky}, \n;


}


HTH...

--
Ankur

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




Re: Reg Closure in Perl

2005-08-25 Thread Ankur Gupta

On 8/25/2005 10:46 AM praba har wrote:


Dear All,

   Kindly let me know what is closure and why we
need it.


People will explain you what it is once you go through the FAQs of this 
mailing list.


http://learn.perl.org/beginners-faq

[...]
2.2 - What is this list _not_ for?

* SPAM
* Homework
* Solicitation
* Things that aren't Perl related
* Monkeys
* Monkeys solicitating homework on non-Perl related SPAM.
[...]

[...]
2.9 Other tips before posting to the list

* Check the FAQs first
* Don't send questions asking ``... will this work?''. Try it 
first, then report errors and ask the list why it *didn't* work. A good 
answer to ``will this work?'', is ``What happened when you tried it?''.
* If your email begins with ``I know this isn't the right place to 
ask this, but...'', don't send it to this list :) If you know it doesn't 
belong, send it to where it does.

* Check the FAQs first
* Look at the archives, 
(http://archive.develooper.com/beginners@perl.org/) to see if your 
question has already been answered on the list.
* Have meaningful Subjects. Subject lines like ``Help!'', and 
``This isn't working!'' may be skipped by many people, and you may not 
get all the great help you want. Try to make your subject lines 
meaningful. For example, ``sprintf() trouble'', or ``Confused about 
formats''.

[...]

--
Ankur

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




RE: Join Function

2005-08-08 Thread Ankur Gupta
Vineet Pande mailto:[EMAIL PROTECTED] wrote:
 hi,
 In the following code which reads a file.txt (SEE ATTACHMENT) where I
 am trying to understand how to put the DNA sequence in to a single
 string...  
 
 print enter file with DNA sequence: ;
 $seqfile = STDIN;
 chomp $seqfile;
 unless ( open(DNAFILE, $seqfile) )
 {
 print can't open!!\n;
 exit;
 }
 @dna = DNAFILE;
 close DNAFILE;

# If only you did the following to remove the newlines from each line of
the file.
chomp(@dna);

 $dna = join( '', @dna);
 print $dna\n;
 
 THE OUTPUT IS EXACTLY THE SAME AS IN file.txt.Why don't we get
 the string joined...of course i agree i must clean whitespace...bu
 then what is expected out of join( '', ). WHAT '' means?  

'' means null string.

HTH...

--Ankur

Quotations are for people who aren't saying things worth quoting.

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




RE: Grep uniqueness issue

2005-07-29 Thread Ankur Gupta
[EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote:
 Hey Guys
 
 I am having an odd problem using grep to ensure an array only
 contains distinct entries. 
 
 I have a list similar to the following in a file (short example of a
 much longer list) 
 
 support01-FastEthernet1/0
 support01-RH
 jnormandin-p370-1691-SH-Cpu-2
 jnormandin-p370-1691-SH
 
 These entries may or may not appear multiple times within that list.
 
 I am trying to create an ARRAY containing each of these entries only
 once (a distinct list). I am using a grep statement: 
 
 push @pingErrorsName, $element if (! grep (/\b$element\b/,
 @pingErrorsName)); 

push @pingErrorsName, $element if ( ! grep { $_ eq $element }
@pingErrorsName );

or 

push @pingErrorsName, $element if ( ! grep { /^$element$/ }
@pingErrorsName );

should work.. (untested though).

But this would be inefficient for large arrays.

Use hash instead.

$pingErrorsName{$element} = undef;

Retrieve the elements by 

@elements = (keys %pingErrorsName);

 * Where $element contains one of the above names in the list and
 @pingErrorsName is the distinct list of elements. 
 
 What I am finding is that the array will contain all of the correct
 entries except: jnormandin-p370-1691-SH. It appears as though the
 grep is matching jnormandin-p370-1691-SH to the
 jnormandin-p370-1691-SH-Cpu-2 string (as it is a substring of the
 second one).   

 Now I am using word boudnary anchors (\b) in the grep so I am
 confused as to why this is not working. 
 
 Does anyone have any ideas as to why this is occuring and how I can
 prevent it? 

HTH...

--Ankur

Why did kamikaze pilots wear helmets anyways?

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




RE: passing hash data from one subroutine to another using refs

2005-07-28 Thread Ankur Gupta
Brent Clark mailto:[EMAIL PROTECTED] wrote:
 Hi

Hi,
 
 Would someone please clear up / help me understand this.

Sure.
 
 I have a hash
 
 my %allTariffData = {};

I think you meant  my %allTariffData = ();

 and in my sub
 
 I have
 my %tariffData = {};

Same here.. my %tariffData = ();

   do the processing etc
   and then
 return \%tariffData;

A reference of %tariffData is returned to the caller.
 
 I now would like to use that data that in tariffData in another
 subroutine. 

I guess your initial subroutine would be like this.

$ref_tariffData = func();
subroutine func returns refernce to a hash.

If you want to use it in another subroutine. simply pass the reference
of that hash to the subroutine.
func2($ref_tariffData);

sub func2 {
my ($ref_hash) = @_;
foreach my $key ( keys %$ref_hash ){
print $key: $ref_hash-{$key}\n;
}
}

 Would anyone be so kind as to share how I would go about this.
 
 I can pass the whole hash, but that would not be right.

You can pass the whole hash but only if you are passing one hash. 
return %hash; # OK
return %hash1, %hash2; # May not be OK

Please read the following perldocs:

perldoc perldsc
perldoc perlref
perldoc perllol
perldoc perldata

It will make the things a lot clearer to you.

--Ankur

I don't suffer from insanity, I enjoy every minute of it!

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




RE: question related to readdir function

2005-07-15 Thread Ankur Gupta
Li, Aiguo (NIH/NCI) mailto:[EMAIL PROTECTED] wrote:
 Dear all.
 
 I wrote a piece of code to read and open all files from a directory
 to do something with it. 
 But I found that the variable assigned to @file_array split the file
 names into pieces.  For example . . test.rpt file will be separated
 into three elements in an array, which are . . test_rpt.  

I guess you are talking about '.' (current directory) and '..' (parent
directory).
I hope you know what they mean. 
If you don't, open a command terminal, cd to C:/perl/work/data/, then
type dir, you will get the three entries which has been captured in the
array.
Like this ...
.
..
test.rpt 

 My question is how can I assign the entire file name to one variable
 without spliting it? 

Your interpretation is wrong.  perl is not splitting your file name into
different strings. 
It is just reading all the file names in that directory.

 Thanks,
 
 AG
 
 #!usr/local/bin/perl
 
 use strict;
 use warnings;
 
 my $dirtoget=C:/perl/work/data/;
 
 opendir (DIR, $dirtoget) or die 'Can not open DIR';
 
 my @file_array;
 
  @file_array =readdir(DIR);
  closedir(DIR);
 
 foreach my $filename (@file_array) {

   ## You don't want to open '.' and '..' directories so ignore them
   next if ( $filename eq '.' || $filename eq '..' );

  print $filename;
 open (IN, $f) || die 'Can not open IN';
 
 while(IN){
 print $_;}
 close(IN);}

This should work.

HTH...

--Ankur

Netnews is like yelling, Anyone want to buy a used car? in a crowded
theater. 

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




RE: sorting list of array

2005-07-13 Thread Ankur Gupta
Beast mailto:[EMAIL PROTECTED] wrote:
 I have an array:
 
 
 my @employee = ( [29243, 'john', 'John doe'],
   [24322, 'jane', 'Jane doe'],
   [27282, 'james', 'James doe']
 );
 
 
 Is there any builtin function in perl to sort the above array based
 on uid, username or fulname? 

perldoc -f sort.

Something like this should work. 

__BEGIN__
use strict;
use warnings;

my @employee = ( [29243, 'john', 'John doe'],
  [24322, 'jane', 'Jane doe'],
  [27282, 'james', 'James doe']
);

# Specify the column on what you want to search as a argument..
my $i = $ARGV[0] || 0;

# sort subroutine..
my $subsort = sub {
#no warnings;
$a-[$i] = $b-[$i]
||
$a-[$i] cmp $b-[$i]
};

print Sorting by column $i\n;
foreach my $j ( sort $subsort @employee ){
print @$j\n;
}
__END__

Some sample runs gave me the following result...

$- test-perl.pl 0
Sorting by column 0
24322 jane Jane doe
27282 james James doe
29243 john John doe

$- test-perl.pl 1
Sorting by column 1
27282 james James doe
24322 jane Jane doe
29243 john John doe

$- test-perl.pl 2
Sorting by column 2
27282 james James doe
24322 jane Jane doe
29243 john John doe

There can be a better way to do it...

HTH

Note: Will give warnings if warnings is enabled for columns which have
text.

--Ankur

Bad style destroys an otherwise superb program.

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




RE: sorting list of array

2005-07-13 Thread Ankur Gupta
Jeff 'japhy' Pinyan mailto:[EMAIL PROTECTED] wrote:
 On Jul 13, Beast said:
 
 Jeff 'japhy' Pinyan wrote:
 
 Is there any builtin function in perl to sort the above array based
 on uid, username or fulname?
 
 There is a built-in function to sort a list, yes.  But the mechanism
 by which to sort the list is, in this case, up to you to provide. 
 This works: 
 
   my @sorted = sort {
 $a-[0] = $b-[0]
   } @employees;
 
 

Hey, This will sort only numbers. Will have no effect if the values have
text.

 However, is this scalable if, for example list is more than 5000 ?
 
 Sure, it's scalable... I believe perl uses a mergesort nowadays,
 which is better on larger lists anyway.  Regardless, given the data
 you showed us, this is the simplest and shortest (and most likely
 fastest) way to sort it based on a given index.   

For more information...

[...]

use sort 'stable';  # guarantee stability
use sort '_quicksort';  # use a quicksort algorithm
use sort '_mergesort';  # use a mergesort algorithm
use sort 'defaults';# revert to default behavior
no  sort 'stable';  # stability not important

use sort '_qsort';  # alias for quicksort

my $current = sort::current();  # identify prevailing algorithm

[...]

--Ankur

Bad style destroys an otherwise superb program.

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




RE: mail header split

2005-06-01 Thread Ankur Gupta
From: John W. Krahn [mailto:[EMAIL PROTECTED] 

 Ankur Gupta wrote:
  
  You can use splice to capture only the relevant fields.
  change it to this...
  
  my ($bookrefNumber) = (split(/-/,$pop3MailContent{'To'}))[0];
 
 You mean a list slice, splice() is a perl function.
 
 perldoc -f splice

Oops... Thanks for correcting... I meant slice only... 

--Ankur 

Scitum est inter caecos luscum regnare posse. (It is well known, that among
the blind the one-eyed man is king.) - Gerard Didier Erasmus
 



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




RE: mail header split

2005-05-31 Thread Ankur Gupta
 I have an email To field that I want regex on
 
 The email is as so:
 
 [EMAIL PROTECTED]
 
 Im trying to get the number before the hyphen.
 
 Currently I have it as so
 
 my ($bookrefNumber, $discard) = split('-',$pop3MailContent{'To'});

You don't need to use $discard variable.

You can use splice to capture only the relevant fields.
change it to this...

my ($bookrefNumber) = (split(/-/,$pop3MailContent{'To'}))[0];

 but I dont like this method.

If you do not like this method then use regexp.

A simple regexp without any checks would be(assuming that all email-ids have
the format you specified). 

# This will capture all the numbers from the starting till it finds a hyphen
(-).
$pop3MailContent{'To'} =~ /^(\d+)-/;

#$1 contains the pattern matched within the parentheses. If no match is
found then $1 would be undef.
my $bookrefNumber = $1;

And if you want, go through perlre/perlretut. It has lots of information on
regular expressions.

--Ankur



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




RE: How to save the state of a CGI script

2005-05-30 Thread Ankur Gupta
From: Randal L. Schwartz [mailto:[EMAIL PROTECTED] 

  Ankur == Ankur Gupta [EMAIL PROTECTED] writes:
 
 Ankur a.cgi calls b.cgi through POST method.
 
 Why?  Why?  CGI is a protocol that permits a server to launch 
 a process to handle a browser hit.
 
 YOU SHOULD NOT HAVE CGI calling EACH OTHER.

Hi Randal,

Let me rephrase. 

I call http://127.0.0.1/a.cgi . This reads a file and based on it creates a
form with select list, popups, text boxes, etc. and a submit button. 

Now this generated html page will call http://127.0.0.1/b.cgi if I click on
the submit button and pass the various parameters using POST method.

I am able to collect the parameters in b.cgi and based on it I am creating a
table(html). Now I want to sort the table on different columns(Details
already provided in my earlier mail). 

I hope I am clear this time. :(

--Ankur 

Emacs is a nice operating system, but I prefer UNIX. - Tom Christiansen



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




RE: How to save the state of a CGI script

2005-05-30 Thread Ankur Gupta
From: David Dorward,,, [mailto:[EMAIL PROTECTED] On Behalf Of 

 On Sat, May 28, 2005 at 09:57:55PM +0530, Ankur Gupta wrote:
 
  I read perldoc CGI and found that state of a script could 
 be saved by 
  the following function.
 
  $myself = $query-self_url;
  print q(a href=$myselfI'm talking to myself./a);
 
 Not quite. If you used qq so that the string would 
 interpolate variables then it would create a link back to the 
 current URL - including the query string.
  
  print $q-start_form(-method='POST',
 
 You cannot create POST requests using a hyperlink, in HTML 
 the only way to set this up is with a form. Additionally, 
 since the data not sent using the query string then simply 
 reading the query string won't include the same values.
 
 You would need to loop through the posted data and generate 
 form controls (such as hidden inputs) for each value. Since 
 the rest of your message discusses sorting of data, you 
 should consider that GET is supposed to be used when 
 retrieving any information from the server and POST when you 
 are changing something. (This has implications such as GET 
 being bookmarkable, and POST causing most browsers to warn 
 about resubmitting data).

Thanks a lot guys for the help. I guess I have to use hidden fields. 

BTW, I am using POST just because there is no restriction on the length of
the query string which I am passing to the cgi script. I read that GET has a
max value but POST does not. Am I right? I have no reservations against
using GET but only because it has max length. My query string can be way too
long that's way I am using POST.

--Ankur 

Where does the family start? It starts with a young man falling in love with
a girl - no superior alternative has yet been found. - Guess what, my ideas
match with Sir Winston Leonard Spencer Churchill



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




RE: How to save the state of a CGI script

2005-05-30 Thread Ankur Gupta
From: Charles K. Clarkson [mailto:[EMAIL PROTECTED] 

 Ankur Gupta mailto:[EMAIL PROTECTED] wrote:
 
 : Thanks a lot guys for the help. I guess I have to use hidden fields.
 
 You could also use a session cookie.

Hi Charles, 

I am fairly new to use the CGI module. So I would like to know how a cookie
would be different from a hidden field.
I mean that I can store all the parameters in the cookie but how can I pass
the parameters to the CGI script.

--Ankur 

Software engineer: One who engineers others into writing the code for
him/her.



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




How to save the state of a CGI script

2005-05-28 Thread Ankur Gupta
Hi,

I am using CGI module.

a.cgi calls b.cgi through POST method. I am collecting all the parameters
using the param function.
b.cgi draws a table based on the input from a.cgi's form. 

The table's row are initially sorted by first column. It is desired that I
can sort the same table by different columns by just clicking on the heading
of the column. 

I read perldoc CGI and found that state of a script could be saved by the
following function.

[...]
$myself = $query-self_url;
print q(a href=$myselfI'm talking to myself./a);

self_url() will return a URL, that, when selected, will reinvoke this script
with all its state information intact. This is most useful when you want to
jump around within the document using internal anchors but you don't want to
disrupt the current contents of the form(s). Something like this will do the
trick.

 $myself = $query-self_url;
 print a href=\$myself#table1\See table 1/a;
 print a href=\$myself#table2\See table 2/a;
 print a href=\$myself#yourself\See for yourself/a;
[...]

But I do not want to jump around the page but change the order of the file.

I tried this stupid thing and it did not work.
my $myself = $q-self_url;
print $q-start_form(-method='POST',
 -action=$myself);

I also read that the parameters can be saved into a file. I tried saving the
parameters and it worked.
But how do I use that information so that I can pass its contents to the
same file.

Kindly help

PS: Earlier I was using GET method and I had one or two parameters to pass.
So I was able to sort on different columns passing the list explicitly.

--Ankur 

Whatever games are played with us, we must play no games with ourselves. -
Ralph Waldo Emerson



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




RE: No appending...

2005-05-28 Thread Ankur Gupta
From: Randal L. Schwartz [mailto:[EMAIL PROTECTED] 

  Wert, == Wert, Nathaniel J [EMAIL PROTECTED] writes:
 
 Wert, Please excuse my lack of knowledge in this subject.  
 The original script
 Wert, executes every statement and in the process, it erases 
 the file when it
 Wert, does the open and then proceeds to not write to the 
 file at all.  Is the
 Wert, text that is supposed to be written to the file stored 
 in a buffer while
 Wert, the program is executing?  I am using the standard 
 Perl mods that came
 Wert, with SuSE SLES 8.0 (perl 5.8).  Is there an upgrade 
 that I sould apply?
 Wert, I assure you that this is the problem.  I change the 
 sleep 1; to
 Wert, system(sleep 1); and the script runs perfectly.
 
 Then the system() is also forcing a flush of all filehandles.  You can
 avoid the external process using the method I gave earlier.  It's
 not the sleep.  It's the lack of unbuffering.

This is what I found in perl561delta. 

[...]

Automatic flushing of output buffers

fork(), exec(), system(), qx//, and pipe open()s now flush buffers of all
files opened for output when the operation was attempted. This mostly
eliminates confusing buffering mishaps suffered by users unaware of how Perl
internally handles I/O.

This is not supported on some platforms like Solaris where a suitably
correct implementation of fflush(NULL) isn't available.

[...]

--Ankur 

William D-FENS Foster:  I'm the bad guy???  How did that happen?



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




RE: on warning die

2005-05-20 Thread Ankur Gupta
 Hello beginners@perl.org,
 
 it is possible to setup somewhere, I want my script dies, if 
 warning occurs.

BEGIN {
$SIG{__WARN__} = sub{ print STDERR @_; exit 1};
}

warn I am going to die\n;

I hope you are looking for something like this.

--Ankur  



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




RE: extracting columns

2005-05-18 Thread Ankur Gupta
From: Aditi Gupta [mailto:[EMAIL PROTECTED] 
 Hi everybody,
  to extract data columnwise from a file, the following code 
 was written with the help of perl experts of this list. the 
 script is as follows:
  
 --
 --
  
 #!usr/bin/perl
 use warnings;
 
 my %hash;
 
 $file= try.txt;
 
 open (FH, $file) or die;
 @rows=FH;
 close (FH);
 
 #$y = scalar(@rows);
 foreach $line (@rows) {
 chomp $line;
 $x = length $line;
 
 for (my $j=0; $j$x; $x++)
 {
 
 # to get value in each column of $line
 
 push @{$hash{$j}}, substr $line,$j,1;
 
 }
 }
 
 foreach my $hkey (keys %hash) {
 print @{$hash{$hkey}}\n;
 
 }
 
 --
 
 
 the code isn't giving any errors but it also isn't printing 
 the result as well. Please someone tell me why is this happeining..

Hi Aditi,

Can you post some data from try.txt file?

Or you can debug your program using perl -d prog.pl args
and step through the program by typing s or n.
This way you would be able to track whether your program is executing all
the expected statements or not.
Go through perldoc perldebug for more information on how to set breakpoints
and display variables, etc.

Or if you are in a unix machine, set environmental var PERLDB_OPTS to N f
A and then just run perl -d prog.pl args.
This will work exactly like csh -x and print all the statements of the
program it is executing.
Or add some print statements in various parts of the program where you think
the problem can be. Something like print I am here.
print this is iteration number $x, $j.

Do not simply die but give some message. Atleast die $! should be enough.

I know you did not ask for an intro on How to debug perl programs but
thought it might be useful. :)

--Ankur 

This planet has -- or rather had -- a problem, which was this: most of the
people living on it were unhappy for pretty much of the time. Many solutions
were suggested for this problem, but most of these were largely concerned
with the movements of small green pieces of paper, which is odd because on
the whole it wasn't the small green pieces of paper that were unhappy.



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




RE: SFTP

2005-05-06 Thread Ankur Gupta
 From: Octavian Rasnita [mailto:[EMAIL PROTECTED] 

 
  good luck with Net::SFTP under windoze. If you will have problems, 
  just look to thread: mid:[EMAIL PROTECTED]
 
 
 
 Thank you. I have found some problems with Net::SFTP under 
 Windows, because it tells me that:
 
 Can't map service name 'ssh' to port number at 
 D:/usr/site/lib/Net/SFTP.pm line 36
 

Make an entry in the WINDOWS\system32\drivers\etc\services file

ssh 22/tcp

Hope this should work.

--Ankur 

Ability is nothing without opportunity. - Napoleon Bonaparte 



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




RE: How would I simulate this in Perl?

2005-05-06 Thread Ankur Gupta
 I have the following find/grep line running just fine from a 
 telnet prompt on the server. I'm trying to include this line 
 into a web app using CFEXECUTE (ColdFusion) but can't get it 
 to work. I know that a compiled perl script would work since 
 I'm already using some previously written ones.
  
 How could I do the following in Perl? I'm searing the 
 directory d:\mywork and all sub-directories within for all 
 the files with a .txt file extension and within those files 
 for the match of 000;
  
 find D:\mywork -name '*.txt' -exec grep '000;' '{}' \; -print

You can use find2perl (installed with perl) to change your find command to
perl's equivalent.

The following returns me the perl code. 

$- find2perl work -name '*.txt' -exec grep '000;' '{}' \; -print

#! /depot/perl-5.6.0/bin/perl -w
eval 'exec /depot/perl-5.6.0/bin/perl -S $0 ${1+$@}'
if 0; #$running_under_some_shell

use strict;
use File::Find ();

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir= *File::Find::dir;
*prune  = *File::Find::prune;


# Traverse desired filesystems
File::Find::find({wanted = \wanted}, 'work');
exit;


sub wanted {
/^.*\.txt\z/s 
doexec(0, 'grep','000;','{}') 
print($name\n);
}


BEGIN {
require Cwd;
my $cwd = Cwd::cwd();
}

sub doexec {
my $ok = shift;
for my $word (@_)
{ $word =~ s#{}#$name#g }
if ($ok) {
my $old = select(STDOUT);
$| = 1;
print @_;
select($old);
return 0 unless STDIN =~ /^y/;
}
chdir $cwd; #sigh
system @_;
chdir $File::Find::dir;
return !$?;
}

--Ankur 

If the automobile had followed the same development cycle as the computer, a
Rolls-Royce would today cost $100, get a million miles per gallon, and
explode once a year, killing everyone inside. - Robert X. Cringely



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




Installing module for different platforms

2005-05-04 Thread Ankur Gupta
Hi,

DynaLoader module is installed for linux platform but not for solaris. I
also want to install it for solaris platform. When I try to install from
solaris platform(through CPAN) then it says DynaLoader is already installed.
I am trying to use GD::Graph module from Solaris platform but seems to give
an error as it could not find DynaLoader in sun4-solaris directory.

FYI.. I am not root and accessing the bin/perl from NFS.

--Ankur 

Those who can, do.  Those who cannot, teach.  Those who cannot teach, HACK!



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




RE: Installing module for different platforms

2005-05-04 Thread Ankur Gupta
 DynaLoader module is installed for linux platform but not for 
 solaris. I also want to install it for solaris platform. When 
 I try to install from solaris platform(through CPAN) then it 
 says DynaLoader is already installed.
 I am trying to use GD::Graph module from Solaris platform but 
 seems to give an error as it could not find DynaLoader in 
 sun4-solaris directory.
 
 FYI.. I am not root and accessing the bin/perl from NFS.

Please ignore my previous mail. It is already installed. Damn!

--Ankur 

Love may not make the world go round, but I must admit that it makes the
ride worthwhile. - Sean Connery 



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




problem with GD

2005-05-04 Thread Ankur Gupta
Hi,

Today I installed gdlib, GD and GD::Graph. There were some problems with
make test but make install went fine. So I installed them forcefully.
Now when I run a sample file from the samples directory I am getting the
following error.

/usr/bin/perl sample63.pl
Processing sample63
ld.so.1: /depot/perl-5.8.3/bin/perl: fatal: relocation error: file
/remote/vtghome6/ankurg/lib/perl5/sun4-solaris/auto/GD/GD.so: symbol
gdFontGetLarge: referenced symbol not found
Killed

I searched in google and got that it has to do something with @LIBS array in
Makefile.PL. It seems libiconv also needs to be present.

I printed the @LIBS array and following is the output. 
-lgd, -lpng, -lz. I I did not have the libiconv library but still the same
problem.

Can someone please help me.. Thanks a lot,

--Ankur 

The opposite of a correct statement is a false statement. But the opposite
of a profound truth may well be another profound truth. - Niels Bohr 



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




RE: Sort array by value length ?

2005-04-22 Thread Ankur Gupta
 Hello,

Hi,
 
 I have an array of names and would like to sort the array by 
 the length of the name but am having difficulty. 
 
 Any suggestions ? 

if you want to sort in ascending order
@sorted = sort { length($a) = length($b) } @unsorted; 

or if in descending order
@sorted = sort { length($b) = length($a) } @unsorted; 

perldoc -f sort will give you many useful examples.

--Ankur



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




How to set system limit through perl

2005-04-21 Thread Ankur Gupta
Hi,

I can set limit on coredumpsize, stacksize, etc. using the limit command.

limit coredumpsize 2048

But how can I do the same thing from a perl script?

I tried Shell::Source but I guess its only for inherting environment. 

TIA.

--Ankur 



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




RE: pointers - references ??

2005-04-11 Thread Ankur Gupta
 If anyone has the time and / or the will to help me understand.
 
 I know how to create / use references for perl. But would why would you
 use it.
 And I think more importantly when.
 
 Im busy reading  / learning the Oreilly Advanced Perl Programming book.
 But for the likes of me I cant undertand when or why I would use it.
 

I will give you one simple example. There are many other uses too :-)

Suppose you want to pass two hashes as arguments to a subroutine. 

sub_hash(%hash1, %hash2);

## You would expect the hashes to capture like the following.. 
sub sub_hash{
my (%hash1, %hash2) = @_;
...
}

But this is incorrect as the arguments will be passed as list and the hashes
that you will try to capture would be lost. 

So here references come to the rescue. 

Pass the hashes as references. 

sub_hash(\%hash1, \%hash2);

sub sub_hash{
my ($rhash1, $rhash2) = @_;
#$rhash1 would be a reference to %hash1... etc.. 
##You can dereference the hashes like this... 
foreach my $key ( keys %{$hash1} ){
...
As you are reading Advanced Perl Programming book, I hope you would find
more examples on how to reference and dereference hashes.

--Ankur




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




Which script called require?

2005-04-06 Thread Ankur Gupta
Hi,

 

I have many perl files which have the following require statement. 

 

require require.file;

 

I just want to know who called require.file in the require.file script. 

 

Right now I am setting an environmental variable in each of the scripts and
checking its value in the require.file. Bad implementation. 

 

TIA.

 

--Ankur



My own die message

2005-03-30 Thread Ankur Gupta
Hi,

 

I have the following code :

 

eval{

 require file or die unable to find file;

};

print $@;

 

But it always prints Can't locate file in @INC. blah blah 

 

I want $@ to contain unable to find file. What am I doing wrong or it is
not possible to override [EMAIL PROTECTED]

 

Thanks,

Ankur



RE: My own die message

2005-03-30 Thread Ankur Gupta
No I do not wanna die so fast.. I want to do some processing based on the
died message.

--
Ankur

-Original Message-
From: Todd de Gruyl [mailto:[EMAIL PROTECTED] 
Sent: Thursday, March 31, 2005 12:24 AM
To: Ankur Gupta
Cc: beginners@perl.org
Subject: Re: My own die message

On 03/30/2005 01:48 PM, Ankur Gupta wrote:
  eval{
 
   require file or die unable to find file;
 
  };
 
  print $@;
 
 
 
  But it always prints Can't locate file in @INC. blah blah 

If you actually want to die, try moving the die outside of the eval:

eval { require file;} or die unable to find file $@;

-- 
Todd de Gruyl

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





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




RE: My own die message

2005-03-30 Thread Ankur Gupta
 -Original Message-
 From: Offer Kaye [mailto:[EMAIL PROTECTED]
 Sent: Thursday, March 31, 2005 2:21 AM
 To: Ankur Gupta; Perl Beginners
 Subject: Re: My own die message
 
 On Thu, 31 Mar 2005 00:18:14 +0530, Ankur Gupta wrote:
  Hi,
 
  I have the following code :
 
  eval{
 
   require file or die unable to find file;
 
  };
 
  print $@;
 
  But it always prints Can't locate file in @INC. blah blah 
 
  I want $@ to contain unable to find file. What am I doing wrong or it
 is
  not possible to override [EMAIL PROTECTED]
 
  Thanks,
 
  Ankur
 
 
 
 Hi Ankur,
 Other people gave you good answers, I just wanted to claify to you why
 your code didn't act as you expected.
 Basically, you have the right idea - a die inside an eval will return
 its argument in the $@ variable. The problem in your code is, your die
 never gets executed! The require, when it fails, dies itself, with
 its own error message - it doesn't return false, so your die never
 gets a chance to execute.
 
 The solution, as other people have said, is simply to handle the
 string outside the eval. Simply put:
 eval {require file};
 print Unable to find file!\n if $@;
 
 See perldoc perlvar for details about $@, perldoc -f eval for more
 info about eval and perldoc -f require for more require info.
 
 Hope this helps,
 --
 Offer Kaye
 
 --
 To unsubscribe, e-mail: [EMAIL PROTECTED]
 For additional commands, e-mail: [EMAIL PROTECTED]
 http://learn.perl.org/ http://learn.perl.org/first-response
 
Thanks Kaye and all,

This helps... 

--
Ankur



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




Internal links with cgi

2005-03-26 Thread Ankur Gupta
Hi,

 

I have a link like this. a href=http://127.0.0.1/link.cgi#word;word/a.

 

When I click on the link word, I want the link.cgi to execute and then it
should navigate to the word word.

 

Link.cgi is executed and everytime it navigates to the top of the page
instead of navigating to the word word. 

Its not happening for me. Is it valid in cgi or am I missing something.

 

Thanks,

Ankur

 



RE: Internal links with cgi

2005-03-26 Thread Ankur Gupta
Thanks David and Bill ...
Using named anchors it worked.. I do not care about old versions of
explorers.

--
Ankur

-Original Message-
From: David Dorward,,, [mailto:[EMAIL PROTECTED] On Behalf Of David Dorward
Sent: Saturday, March 26, 2005 11:17 PM
To: Ankur Gupta
Cc: beginners-cgi@perl.org
Subject: Re: Internal links with cgi

On Sat, Mar 26, 2005 at 11:11:15PM +0530, Ankur Gupta wrote:

 I have a link like this. a
href=http://127.0.0.1/link.cgi#word;word/a.

 When I click on the link word, I want the link.cgi to execute and then it
 should navigate to the word word.

Then wrap that word in a named anchor or (if you are writing modern
code and don't need to support browsers as obsolete as Netscape 4) a
suitable element with an id.
 
 Its not happening for me. Is it valid in cgi or am I missing something.

All the browser knows is that it has recieved some HTML because it
made a request for an HTTP resource. It doesn't matter how the server
goes about working out what content to send back, CGI, mod_perl, a
static file, its all the same to the client.

-- 
David Dorward  http://dorward.me.uk




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




Re: regexp help

2005-03-11 Thread Ankur Gupta
radhika wrote:
Hi,
I need to parse this string: 2005-03-11 13:49:41.19
to just get the hour and minute.
my program has:
if( $string = /([\d]+)-([\d]+)-([\d]+)\s([\d\d):(\d\d):(\w+)/ )
I guess it should have been =~ instead of =
{
  print(Hour:Minute = $4:$5\n);
}
if ( $string =~ /.*\s+(\d\d):(\d\d):.*$/ ){
print(Hour:Minute = $1:$2\n);
}
This should work.
Ankur

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



Re: output from system call

2005-03-08 Thread Ankur Gupta
[EMAIL PROTECTED] wrote:
Hi,
Is there a way to store the output of a system call on unix?
eg. system(date);
use backticks...
$date = `date`;
Don't forget to chomp the $date variable as I guess you just want the date, not 
the newline character with it...
chomp($date);

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



Re: tricky hash

2005-03-08 Thread Ankur Gupta
Ing. Branislav Gerzo wrote:
Hello beginners@perl.org,
anyone could me help with:
use strict;
use warnings;
my %kw = ();
my $kw = \%kw;
for my $cat (split(/\//, 'something/other/foo/bar')) { $kw-{cnt}++; 
$kw-{cat${kw-{cnt}}} = $cat }
Change this line to 

 for my $cat (split(/\//, 'something/other/foo/bar')) { $kw-{cnt}++; $kw-{cat 
. $kw-{cnt}} = $cat }
This should work.

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



Re: Understanding split in a while loop

2005-02-28 Thread Ankur Gupta

I am not sure why? It misses the odd ones.
while (PASSWD) {
my @passwds = split /:/, PASSWD;
You are reading the file twice in each while loop. Whenever you access 
PASSWD, it returns a line and moves to the next line of the file.
So in while (PASSWD) { it returns one line of the passwd file  .
As you are reading the line again in my @passwds = split /:/, PASSWD;, you 
are missing out on the previous line.
print @passwds;
}

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



Re: Load an hash from a text file

2005-02-28 Thread Ankur Gupta
Web Solving wrote:
i rebuilt the scipt without using any hash in this way:
open(INFILE,lista.txt) || die Cant read lista.txt. Reason: $!; 

while( INFILE ){  

 Where is the closing braces for this while loop
  my ($search, $replace) = split /|/;
open(READIT,testo.txt) || die Cant read file.txt. Reason: $!; 
open(WRITEIT,testo_new.txt) || die Cant write file_new.txt. Reason: $!; 
while (READIT) { 
  $riga = $_;
  $riga =~ s/$search/$replace/; 
  
  print WRITEIT $riga\n; 
   

} 
close(WRITEIT); 
close(READIT); 
 

} --- Please add this

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



Re: capture output in perl

2005-02-28 Thread Ankur Gupta
[EMAIL PROTECTED] wrote:
hi,
I would like to capture all the output in my perl program during execution. I have code that basically opens and closes an output file multiple times just to write the output. Because I have system calls between lines of code, I have to close the file in order to capture the output from the system calls and write it to the same file (in this case /tmp/tmp.log) . 

Not an elegant code. Is there a better way of rewriting the code?  

Add this to the top:
$| = 1; (To flush the output so that the order of print statement is maintained)
open(STDSAVE, STDOUT); # Duplicate your STDOUT filehandle incase you want 
to print something on the screen.
open(STDOUT,/tmp/tmp.log); # Open your log file with STDOUT as the 
filehandle
#Everything that you print now would go to log file now.
#Along with the output of the system command.
#Now remove all instances of OUTF from the code.
   print OUTF i=10\n\n;
to
print i=10\n\n;
#Also remove all redirection of the your system commands output to the log file
system (ls nofile.txt 2 /tmp/tmp.log);
to
system (ls nofile.txt 2);
Incase you want to print to the screen. 
Use print STDSAVE HEllo there\n; # Would print on the screen.
In case you want to close the log file and restore to the normal printing.
close(STDOUT);
open(STDOUT,STDSAVE);

One more thing: If you want to print your output to the screen as well as to 
the log file.
Use open(STDOUT, | tee /tmp/tmp.log STDOUT);
So whatever you print would go to the screen as well as to the log file. (-- 
Taken from Perl Cookbook)
Same you can do with the STDERR to capture your warnings and errors to a 
separate error log file.
HTH
--
Ankur

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



Re: Verify that a directory exists.

2005-02-28 Thread Ankur Gupta
Carlos Mantero wrote:
El lun, 28-02-2005 a las 14:49 +0300, Vladimir D Belousov escribió:
 

1)
  if (-d $DIR_NAME) {
  directory exists
   };
2)
 if((lstat($DIR_NAME))[1]  004) {
 directory exists and it is the real directory (not the 
symbolic link)
 }else{
... No such directory or it is symbolic link
 };

Carlos Mantero wrote:
   

Hi all,
I'm a begginer in Perl and other programming languages. I want to verify
that a directory exists, but I don't know the way tho do it.
Regards.
 

Hi, I tested the code in my little script but the if bucle with the
verify of the directory don't work fine, always print 1.
if (-d /home/user) {
-d /home/user is a string and not a test of directory.
So it would always return true.
So use if (-d /home/user){ 
and you would know the problem. 

	print1\n;
}
 

Also, if you are hard coding the path then you need to quote them
if (-d /home/user){
if you are using a variable then
if (-d $dir){ 
would work.
But its always a good practice to quote filenames/directories , even if they are variables.




Re: Verify that a directory exists.

2005-02-28 Thread Ankur Gupta

Also, if you are hard coding the path then you need to quote them if
(-d /home/user){ if you are using a variable then if (-d $dir){
would work. But its always a good practice to quote
filenames/directories , even if they are variables.
   

What? You mean like:
if (-d $dir) { ...
Why do you think so???
Nothing in particular.. 
Sometimes I use 
if(-d $dir/test){
... This fails

So its better to use 
if(-d $dir/test) { 

No problemo...


Re: Verify that a directory exists.

2005-02-28 Thread Ankur Gupta

So its better to use 
if(-d $dir/test) { 
   

I see. Well I would not call this good practice. You simply have to 
quote the string literal. 
Or construct it via concatenation:

	if(-d ($dir . /test)) { 

I would use the first form. Anyway my point was that you should not 
quote a simple variable:
	if (-d $dir) { ...
Unless you really really know why.

Yeah.. Makes sense. Thanks.. 




Re: printing output of ping command

2005-02-23 Thread Ankur Gupta
TapasranjanMohapatra wrote:
Hi All,
I have a script as follows

my $host = shift;
my $count = shift;
my $result = `ping -c $count $host`;
if($result =~ m/$count packets transmitted, $count packets received/)
{
$success = 1;
}
print $result\n;

Now, when I run the script, the ping is executed the result is stored in the 
$result variable and printed at the last statement. When the count is a big 
number, I have to wait till the command finishes and then it prints at one shot 
at the last line.
Is it possible to get the output printed as it is seen while running the ping 
command? I mean instead of printing at one shot at the end, I want to print 
line by line as the ping is being executed. Is it possible?
TIA
Tapas
 

sure this is possible..
$|=1;
open (PING, ping -c $count $host |) or die Cannot execute ping:$!\n;
while(PING){
print;
}

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



Re: Never done perl before

2005-02-18 Thread Ankur Gupta
Lucio Crusca wrote:
Perl newbie is way too much when referred to me. I've never even thought
to try to understand a single character of a perl program. Now I need to.
But, still, I don't want. I live more than well with my knowledge of other
languages.
However I'm facing a wonderful Courier ESMTP setup that requires me to use
perl in order to write a filter. And I don't want to use perl. So I could
use one single perl operator I've found: backticks.
What I need is to call an external executable passing a filename as the only
argument and then returning its output to the caller of the perl script,
e.g:
$reply=`myfilter.sh $filename`;
print $reply;
Is the above code correct for my purpose (assuming $filename is defined)?
 

why don't you try it out yourself and enlighten us... 


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



Re: How to add leading zeros?

2005-02-16 Thread Ankur Gupta
Bastian Angerstein wrote:
Hello,
I have some Numbers  1 2 3 40 51 and I want them to be in the format 
001 002 003 ... 040 ... 051 ...

What is the fastest way to do this??
use sprintf
$num = 1;
$zero_num = sprintf(%03d, $num);
#$zero_num will now have 001
perldoc -f sprintf
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: Idiomatic Perl for GPA Calculation

2005-02-16 Thread Ankur Gupta

#!/usr/bin/perl
# This is the GPA calculation routine for the
# Eduadmin system again.
#
$ifile = 'gpa.dat';
open (INF, $ifile) || die Can't open file $ifile:$!\n;
$cp_total = 0;
$id = 0;
$temp = 0;
LINE:  while (INF) { ($id, $grade, $cp) = 
split; 
  if ($grade =~ /NG/i   ||
  $grade =~ /YL/i   ||
  $grade =~ /DF/i   ||
  $grade =~ /\bY\b/i||
  $grade =~ /W/i||
  $grade =~ /T/i) {next LINE;}

  $cp_total += 
$cp;   
   if ($grade =~ /\bA\b/i) {  $a6++ if $cp == 
6;$a4++ if $cp == 
4;$a3++ if $cp == 
3;$a2++ if $cp == 
2;  }
if ($grade =~ /\bB\b/i) {  $b6++ if 
$cp == 6;$b4++ if $cp == 
4;$b3++ if $cp == 
3;$b2++ if $cp == 
2;  }

   if ($grade =~ /\bC\b/i) {  $c6++ if $cp == 
6;$c4++ if $cp == 
4;$c3++ if $cp == 
3;$c2++ if $cp == 
2;  }

   if ($grade =~ /\bD\b/i) {  $d6++ if $cp == 
6;$d4++ if $cp == 
4;$d3++ if $cp == 
3;$d2++ if $cp == 
2;  }

  if ($temp == $id) {
 next LINE;
   }
  else {
$wcp = ($a6*4.0*6.0 + $a4*4.0*4.0 + $a3*4.0*3.0 + $a2*4.0*2.0) +
   ($b6*3.0*6.0 + $b4*3.0*4.0 + $b3*3.0*3.0 + $b2*3.0*2.0) +
   ($c6*2.0*6.0 + $c4*2.0*4.0 + $c3*2.0*3.0 + $c2*2.0*2.0) +
   ($d6*1.0*6.0 + $d4*1.0*4.0 + $d3*1.0*3.0 + $d2*1.0*2.0);
$gpa = $wcp / $cp_total;
   $temp = $id;
   $cp_total = 0;
   next LINE;
  }
} # end of while
use hashes of hashes.
#Lets first store the hashes
while(INF){
   ($id, $grade, $cp) = split(/\s+/);
   #I am removing the .00 for convenience. You can preserve it and make 
changes accordingly
   $cp =~ s/(\d)\.00/$1/;
   #No need for label.. lets put everything in one search
   next if  $grade =~ /(NG|YL|DF|\bY\b|W|T)/ ;
   #This is the best part.. I am creating hashes of hashes of hashes. 
The hashes takes care of uniqueness.
   $student{$id}-{$grade}-{$cp}++;
   #Simple hash for sum of credit points
   $cp_total{$id} += $cp;
}

#Now calculate the weighted credit points for each student..
foreach $id ( keys %student ){
   #Even this can be improved by using more foreaches. But lets keep it 
like this for easy readability
   $wcp = ($student{$id}-{A}-{6}*24 + $student{$id}-{A}-{4}*16 + 
$student{$id}-{A}-{3}*12 + $student{$id}-{A}-{2}*8)+
($student{$id}-{B}-{6}*18 + 
$student{$id}-{B}-{4}*12 + $student{$id}-{B}-{3}*9 + 
$student{$id}-{B}-{2}*6)+
($student{$id}-{C}-{6}*12 + $student{$id}-{C}-{4}*8 
+ $student{$id}-{C}-{3}*6 + $student{$id}-{C}-{2}*6)+
($student{$id}-{D}-{6}*6 + $student{$id}-{D}-{4}*4 
+ $student{$id}-{D}-{3}*3 + $student{$id}-{D}-{2}*2);
   #Calculate the gpa and store it for each student
   $gpa{$id} = $wcp/$cp_total{$id};
}

#Lets print it now. We could have done it in the above foreach also ..
foreach $id (keys %student){
   print GPA for $id : $gpa{$id}\n;
}
BTW, I got these values
GPA for 216 : 1.98
GPA for 386 : 1.40
Although it is correct for 386.. it does not matches for id 216. Are you 
sure gpa for 216 is correct.

Hope you got the idea of how you can use hashes to make the program 
short and simple.

--
Ankur

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



Re: getting +*-/ from $operator=STDIN in print

2005-02-15 Thread Ankur Gupta

print First value: ;
chomp ($value1=STDIN;
print Second Value: ;
chomp ($value2=STDIN;
print Operator: ;
chomp ($value3=STDIN;
print ($value1 $value3 $value2, \n);
But that was malfaunctioning. Is there a way to put the STDIN for the
operator directly in the print line or do I always have to keep it that long
winded?
Oliver
 

use eval..
print Enter a expression to calculate:\n;
$expression = STDIN;
chomp($expression);
print eval($expression), \n;
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: Request for regex: Strip last dash in a record

2005-02-15 Thread Ankur Gupta
[EMAIL PROTECTED] wrote:
[EMAIL PROTECTED] wrote:
   

Hi All,
The code below does what I want to do, but it takes 3 lines and a
 

temporary
 

array (yuck).  I can't come up with a one line regex substitution.
 

Anyone
 

got one?
my $tmp = reverse split //, $_;
$tmp =~ s/-//;
$_ = reverse split //, $tmp;
 

can you post a sample string which you want to substitute..
   

sure.
Example record:
0-0-0-EXAMPLE-00-621
Will become:
0-0-0-EXAMPLE-00621
If you just want to remove the last occuring '-' character, then the 
following would work.

s/(.*)-(.*)/$1$2/;


Re: how to use hash as parameter

2005-01-31 Thread Ankur Gupta
#!/usr/bin/perl
my %hs;
$hs{one} = 1;
$hs{two} = 2;

sub pr
{
my $ref = $_;

foreach $key (sort keys %$ref)
{
print $key = ${$ref{$key}}; }
}

pr(\%hs);

This should work..

--
Ankur

Hou Feng.Leo wrote:

 Dear all,
 I want to pass a hash to a function which prints out hash's content.
 My code does not work. Can anyone tell me what is wrong with it?
 Thanks a lot


 #!/usr/bin/perl
 my %hs;
 $hs{one} = 1;
 $hs{two} = 2;

 sub pr
 {
 my $ref = $_;

 foreach $key (sort keys %ref)
 {
 print $key = $ref{$key}; }
 }

 pr(\%hs);






Re: flush function

2005-01-31 Thread Ankur Gupta
Urs Wagner wrote:
Hello
I have a problem on WinXP. In perl I want to read the tail of a file. 
The  file is written with another windows
program. If I am using a sleep(5) before of the read command I get the 
new tail content. It seems the program
has longer to write it or it is buffered.
Is there a command in perl to flush a file?

Thanks
Urs
to flush the contents, set at the top of your perl program.
$| = 1;
HTH
--
Ankur
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: Bareword INPUT not allowed while strict subs

2005-01-27 Thread Ankur Gupta
I think you can't pass filehandles directly to a sub.
You need to use typeglob.
Just add this after opening the file.
my $file = *INPUT;
$message = processTextMails($file);
sub processTextMails
{
my $file = shift;
 while($file)
 {
  $returnMessage=$returnMessage.$_;
 }
 close($file);
 return $returnMessage;
}
I hope this works.
--
Ankur
Anish Kumar K. wrote:
Hi
I open a file and pass the file handle to the sub routine. I have used Use 
Strict
I am getting the error in the filehandle. Why is this caused.. Is it because I 
need to pass any other information with this
sub processTextMails
{
 while(INPUT)
 {
  $returnMessage=$returnMessage.$_;
 }
 close(INPUT);
 return $returnMessage;
}
Other routine
open (INPUT , a.txt) II die Cannot open this file;
$message = processTextMails(INPUT); = Error in this line
Bareword INPUT not allowed while strict subs in use at 

Thanks
Anish
 


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



Re: How to find the Index of an element in array?

2005-01-27 Thread Ankur Gupta
I have another solution using grep but its kinda weird
@array = (..); #your array here
$i=1;
eval{
grep { (/$element/o  die ) or ++$i } @array;
};
print index of $element = $i\n; #prints the index of $element.. If $i 
 scalar(@array), element not found.

--
Ankur
Manav Mathur wrote:
Rob, In your solution
$hash{'pqr'} will return 3. 
- iniitalize $i with 1
or
-
%hash=map{$_=[EMAIL PROTECTED];

Manav
|-Original Message-
|From: Rob Napier [mailto:[EMAIL PROTECTED]
|Sent: Thursday, January 27, 2005 2:06 PM
|To: Richard Chycoski
|Cc: Mallik; Perl-Trolls; beginners@perl.org
|Subject: Re: How to find the Index of an element in array?
|
|
|In terms of time efficiency, if you only need one lookup, the linear 
|walk is almost certainly faster, since you don't have to hash the entire 
|list. You can stop as soon as you find the answer (which you expect to 
|be half-way down the list). But the speed difference is almost certainly 
|negligable. In terms of space efficiency the array is much smaller too 
|which matters if the hash gets particularly large (large enough that the 
|speed difference isn't negligable).
|
|I agree with depending on what else you need to do with your data. If 
|a list is more natural for the data, definitely leave it in a list and 
|just walk it. If you need to do a lot of lookups (or other hash-like 
|things), you can hash the list as Richard suggests pretty easily:
|
|my $i = 0;
|my %hash = map { $_ = $i++ } @list;
|print $hash{$search};
|
|And of course the above is short and simple, so maybe that's nice even 
|if you're only doing it once and don't mind being slower and bigger 
|(memorywise).
|
|If you want to stay with a fast linear search, there have been a couple 
|of good suggestions. Tapasranjan's version is close, but does too much 
|searching. You should do a 'last' after you've found the data. Arjun's 
|solution is good, or you can do this kind of shortened form:
|
|my $search = 'pqr';
|for(my $i = 0; $i  @arr; $i++)
|{
|($arr[$i] eq $search)  do { print index is == $i\n; last }
|}
|
|Note that in this form, $i is not valid outside the loop. You'll need to 
|move the my $i outside the for() loop if you need it later in the code.
|
|-RobN
|
|Richard Chycoski wrote:
| You would have to 'walk' the whole array, which is rather inefficient. 
| However, depending on what else you need to do with your data, a hash 
| could do better than an array:
| 
| %myhash = ('abc'=1, 'xyz'=2, 'mno'=3, 'pqr'=4, 'stu'=5, 'sdfd'=6);
| 
| and then
| $myhash{ 'pqr') wiil return 4.
| 
| - Richard
| 
| 
| Mallik wrote:
| 
| I need to find the index of a particular element in array.
| For eg.,
| @arr = ('abc', 'xyz', 'mno','pqr','stu','sdfd');
|
| I want to find the index of the element 'pqr' which is 4.
|
| Any function/code to achieve this.
|
| Thanks in advance,
| Mallik.
|  
|
| 
|
|-- 
|To unsubscribe, e-mail: [EMAIL PROTECTED]
|For additional commands, e-mail: [EMAIL PROTECTED]
|http://learn.perl.org/ http://learn.perl.org/first-response
|
|

*
Disclaimer:  

This message (including any attachments) contains 
confidential information intended for a specific 
individual and purpose, and is protected by law. 
If you are not the intended recipient, you should 
delete this message and are hereby notified that 
any disclosure, copying, or distribution of this
message, or the taking of any action based on it, 
is strictly prohibited.

*
Visit us at http://www.mahindrabt.com
 


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



Re: hashes of arrays?

2005-01-25 Thread Ankur Gupta

It is possible to store an array in a hash by using references
#foreach $destination (@dest_users) {  # NO NEED FOR THIS
  #print ==$destination\n;  
push( @{$aliases{$alias}}, @dest_users );
foreach $key ( keys %aliases ){
   print $key: @{$aliases{$key}}\n;
}
HTH
--
Ankur
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Slow SFTP rate through perl script.

2004-07-15 Thread Ankur Gupta
Hi,
 
I have a script which downloads a file from a sftp server. But it takes
almost 2-3 hours to download a file of 40mb.. while I am able to download
the same file though SSH Client in 15-20 minutes. Any clues why it is
happening so.. 
 
Thanks,
Ankur