Re: (OS=winxp) system cmd dies but performs the command
Harry Putnam wrote: I'm not used to writing perl scripts on windows. I'm having a problem where a system call dies but still performs the command. I don't think I understand how exit status is checked. my $target = E:/some_dir/another_dir; system(mkdir $target) or die Can't mkdir $target: $!; The script stops at the `or die' but looking in E:/ I see `dir' has been created. Also the error ouput ($!) has no value. I get this error: Can't mkdir E:/some_dir/another_dir At: blah blah line 23 So the command didn't really fail but perl thinks it did. May be notable that the script is running on C: and the target is on E: I'd suggest taking John's advice, and using native Perl functions. OTOH, you could also try: system(md $target) and die Can't mkdir $target:; Which would provide the effect you are seeking. Greetings! E:\d_drive\perlStuffperl -w my $target = 'test'; system(mkdir $target) and die Can't mkdir $target; ^Z A subdirectory or file test already exists. Can't mkdir test at - line 2. Note that $! is not usable, and may be counerproductive, in this context: Greetings! E:\d_drive\perlStuffperl -w my $target = 'test'; system(mkdir $target) and die Can't mkdir $target: $!; ^Z A subdirectory or file test already exists. Can't mkdir test: No such file or directory at - line 2. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: determining size of array through reference
Andrew Gaffney wrote: david wrote: Andrew Gaffney wrote: I've got an array reference and I'm trying to figure out how many elements are in it. I've tried '$#arrayref', '[EMAIL PROTECTED]', '$(@($arrayref))', and probably a few others that I've forgotten. What is the correct way to do this? you can try @{EXP} or $#{EXP}+1 where EXP is your array reference: [panda]# perl -le 'print $#{[1,3,5,7]}+1' 4 [panda]# perl -le 'print @{[1,3,5,7]}+0' 4 [panda]# the '{}' is sometimes optional depends on EXP, i usually use it for personal perference. '$#{$arrayref}+1' worked for me. Thanks. Once again, I don't know what I'd do without the people on this list. Way too complicaqted, I'd say. Just put it in scalar context by assigning the array referenced by it to a scalar: Greetings! E:\d_drive\perlStuffperl -w -Mstrict my @elements = (1, 'two', 'three', 4); my $array_ref = [EMAIL PROTECTED]; my $count = @$array_ref; print $count\n; ^Z 4 Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Questions about game design in perl
Morbus Iff wrote: I am trying to build a game in perl. I have questions. This is a story book game... here is the story, make a choice next page..here is the story, make a choice I'd love to see what you come up with. Games and Perl is close to my heart. WTF does this have to do with the confusion between NULL and Perl's udef [New To Perl], the thread on which you replied? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Questions about game design in perl
R. Joseph Newton wrote: Morbus Iff wrote: I am trying to build a game in perl. I have questions. This is a story book game... here is the story, make a choice next page..here is the story, make a choice I'd love to see what you come up with. Games and Perl is close to my heart. WTF does this have to do with the confusion between NULL and Perl's udef [New To Perl], the thread on which you replied? Joseph Sorry, I sanpped at the wrong post. Still I wish those replying had redirected this back to the main index [by start a new message using the title line] before replying Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Regular expression question: non-greedy matches
Boris Shor wrote: Thanks for writing. Hi Boris, Please don't top-post. It makes it very difficult to get the context of your message. Istead, post following the material to which you are responding. Your code works for this example but doesn't get exactly what I need. It's important to me to keep $1 and $2 separate because Yeas and Nays are paired together (these are votes on bills). But sometimes, you only have Yeas (eg, a unanimous vote). That is why I want to see: 123 - from the first yea ($1) (nothing) - no nay! ($2) 456 - from the second yea ($1) 789 - from the second nay ($2) Why would you want to do this? It seems to me that this is taking information and truning it into meaningless data. A series of numbers piled on top of each other doesn't really communicate much. What do you want to get out of the process as a whole? Hence why I put a ? After the (?:Nay (.*?)x) regexp; That is a bit off. I think we really need a sample of actual data to be able to help you. If the data is of a confidential nature, then you will have to do meaningful substitutions for any matter that is not public. Boilerplate substitutions do not work. So far, I have seen three different formats for your sample string. Each of them would call logically for a somewhat different extraction approach. . My best advice would be not to do it all in one regex. Regular expressions are powerful tools, and amaxingly efficient given the demands placed on them, but they get progressively less efficient as they increase in complexity. If there is any distinct marker that separates the items being voted on, I would strongly recommend that you first split on this marker so that each vote ahs its own element. It is much better to have explicit 0's for the losing side in any unanimous vote. Undefined values only confuse issues. the idea being this can appear zero or one times. But if I do this, I get no matches on the 'nays' or $2. That is a pretty strong indication that the single-regex approach is not the way to go for this job. Can you give us a little more information on what your are trying to accomplish overall? You get there much faster when you know your destination. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: using strict
[EMAIL PROTECTED] wrote: Yet another great explanation.. What explanation? I see niothing above this. Please do not top-post when posting to this list. Instead, follow the material to which you are directly responding with your response, then trim any extraneous material. Most of us keep records of recent posts, and newsreaders will also thread them appropriately, so if people need the entire text of an original post, they can refer to it. . thank you! But I still need to know how to print each specific element # along with its data? Is this the right way to go for storing each line in its own element??? while $line FILEHANDLE my @tsm = FILEHANDLE Which do you want? This is a repeat of the same problem in your earlier post. Do each task once, and only once foreach $_ (@tsm) If you explicitly assign a variable out of a for loop, make it a meaningful and descriptive variable name. The default variable is assigned automatically if you do not provide a variable to receive the values produced. Either: foraeach (@tsm) { # pronounce the word tsm aloud. Now say it ten time, fast. do something($_) } or foreach $thing_going_bump (@things_that_go_bump_in_the_night) { if (is_significant($thing_going_bump) { investigate_and_confront($thing_going_bump) } else { go_back_to_sleep(); } } Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: using strict
Guay Jean-Sébastien wrote: Hello Derek, Guay, Err, my first name is Jean-Sebastien. Hi Jean-Sebastien, My last name is Guay. French-language people have a bad habit to put the last name first, as in Guay, Jean-Sebastien... So I understand why this is a bit confusing. Thanks for the clarification. It is nice to know how to address each other. One thing I would request is that you trim off any material to which you are not responding from old posts. This helps keep bandwidth and storage needs down. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: using strict
david wrote: Guay Jean-Sébastien wrote: open (CRITICALSERVERS, $crout) || die can't open file \n: $!; As I said, you should replace || by or in the above line. See the precedence rules in perldoc perlop for details. why do you think so? is there any problem in the above line? Good point. The explcit parentheses do indeed avoid the precedence problems that would come with: open CRITICALSERVERS, $crout || die can't open file \n: $!; Where the open function would take the second line as an alternative argument. For instance, I have no file named 'crout' in my filesystem, yet: Greetings! E:\d_drive\perlStuffperl -w open CRITICALSERVERS, 'crout' || die can't open file \n: $!; close CRITICALSERVERS; ^Z does not produce an error message, because the die clause gets taken as an alternative. A stronger argument has to do with mindset. The || operator is an expression evaluation operator, appropriate to mathematical or paramathematical expressions. The context really calls for a flow-control operator, or. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: using strict
Guay Jean-Sébastien wrote: There is no problem syntactically. But there is a problem with the precdence. If you ever have another operation on either the left or right side of the || operator, the || operator will bind tighter than the other operation. So for example, if you do: my $errors = 0; open (CRITICALSERVERS, $crout) || $errors += 2; that will translate to: my $errors = 0; ( open (CRITICALSERVERS, $crout) || $errors ) += 2; Nope. Please credit the Perl interpreter with some common sense. There are few, if any, instances where Perl would override explicit parentheses, and does not in this case. To illustrate, I restore the parens to the example I used in a parallel response: Greetings! E:\d_drive\perlStuffperl -w open (CRITICALSERVERS, 'crout') || die can't open file \n: $!; close CRITICALSERVERS; ^Z can't open file : No such file or directory at - line 1. In most cases, Perl will do the right thing with statements expressed in natural form. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Help with pattern matching
A Lukaszewski wrote: Greetings all, I have a comma-delimited lexical file with four fields: line number, the first part of a word, the second part of a word, and the word combined. The first and fourth fields are only for reference. The program I am developing is very simple. If field two and field three both have accents in them, then print the line to an output file. That is noce, but where is the sample data? It is almost impossible to debug input-processing code if you cannot see the material being processed. Some errors are glaring suntax errors, but many involve a disconnect between the code and the material being processed. The heavily-commented program is below. Thus far, all I get is an exact replica of the input file. In addition to a plain binding operator of '=~ //', I have also tried explicit matching (m//) and regex (qr//). #!/usr/bin/perl # # # A PROGRAM TO READ THE SUB-WORD HEADERS OF A # # COMMA-DELIMITED FILE # # AND DETERMINE WHICH LINES HAVE MULTIPLE ACCENTS # # # use strict; ### # OPEN THE INPUT AND OUTPUT FILES # ### my ($file, $outfile); $file= 'y.csv' ; # Name the input file $outfile = 'y.res'; # Name the output file open(INFO, $file ) or die Cannot open $file:$!\n; # Open the input file or report failure open(OUT, $outfile) or die Cannot open file y.res!\n; # Open the output file # INITIALIZATION OF SCALARS AND ARRAYS # my $line; # = scalar by which program steps through data my $fieldEval1; # = holding scalar for evaluating whether the # first half of the word has an accent in it my $fieldEval2; # = holding scalar for evaluating whether the # second half of the word has an accent in it my @field;# = holding array for the split line Two ajor differences in convention between Perl and VB: In Perl, CamelBack is generall reserved for package [aka class] names. Variables should take $choo_choo_train style. Folowing this convention will make your code much more understandable to other Perl programmers. In Perl, there is no need to lump are your declarations at the top of a scope, where their meaning must be expressed in comments. Put the life and meaning in the code itself, by declaring meaningfully-named variables at the point closest to their initial use. This makes the code much more understandable. open WORD_PARTS, 'some_better_name_than_just_y.csv' or die could not open parsed word file for input: $!; open DOUBLE_ACCENTED_OUT, 'double_acented_words.res' or die Could not open results file for output: $!; while (my $parsed_word = WORD_PARTS) { chomp $parsed_word; my ($line_id, $first_part, $second_part, $whole_word) = split /,\s*/, $parsed_word; if (both_are_accented( $first_part, $second_part ) { print DOUBLE_ACCENTED_OUT, $parsed_word; } } You will note that there are no comments in the code above. Do you have any difficulty understanding what it does? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Using $_ in a function if no argument is passed
Paul Johnson wrote: On Sat, Apr 03, 2004 at 11:53:59AM -0800, R. Joseph Newton wrote: Paul Johnson wrote: $_ = Leave me alone!; $s = 0; Better yet: $lower_or-mixed_case_string = 'o'; I worry that you may have missed the point of the example, which was the value of the variable being passed into the to_upper subroutine. That has since been discussed elsewhere in this thread, but you could argue that I should have been more explicit. Not really. Ithought you addressed that quite well. A couple of interesting points he makes on variable name length are that the length of a variable name should reflect the scope of the variable. A short variable name is fine in a restricted scope. For a larger scope, use a longer name. I always start global variables with a capital letter. I can see how the meaning of a variable is less likely to be lost in a narrow scope. I still think it is better to use the language to express meaning as clearly and naturally as possible. In my view, the biggest stumbling block for beginners is a sort of techno-fetishism, almost a subconcious belief that there is some gain in efficiency from saving keystrokes. Meantime, they get distracted from the actual flow of logic. I know my examples are a bit exxagerated, but I do think beginners will benefit by using a more plain-language approach. He also mantions that i is often a very good name for a loop variable in a restricted scope. Absolutely. There are a few, like i for the loop iterator, and x and y for Cartesian coordinates, that are so uniquitous as to be immediately identifiable. I would still sugest that literals should be kept to very familiar mathematical constructs. The first edition was very good. The second looks like it will be even better. Well, if my income ever allows for buying books, I will have to take a look. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nested parens
Charles K. Clarkson wrote: JupiterHost.Net [EMAIL PROTECTED] wrote: : : [EMAIL PROTECTED] wrote: : Is there a module out there that I can use to parse : a text line and return the pieces that are enclosed : in paren's? : : You don't need a module for that just use regex's: : : my @text_inside_parens = $string =~ m/\((.*)\)/g; Let's test it. use strict; use warnings; use Data::Dumper 'Dumper'; foreach my $string ( '(foo) (bar)', '(foo) (bar) (baz)', '((foo) bar)) (baz)', '(foo bar)',) { my @text_inside_parens = $string =~ m/\((.*)\)/g; print Dumper [EMAIL PROTECTED]; } __END__ I get: $VAR1 = [ 'foo) (bar' I see. Someone dun fergot the lazy symbol, huh? ... .* is greedy. I suspect @text_inside_parens will never have more than one element in it. good point. ... my @text_inside_parens = $string =~ m/\((.*?)\)/g; print Dumper [EMAIL PROTECTED]; } __END__ $VAR1 = [ 'foo', 'bar' ]; $VAR1 = [ 'foo', 'bar', 'baz' ]; ... Joseph -- 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 file handles into modules
[EMAIL PROTECTED] wrote: Unfourtunately, the code is on an isolated PC. Post again from the machine your script is on, or use some transfer machine to move it to the machine you post from. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: using strict
Paul Johnson wrote: On Sun, Apr 04, 2004 at 01:28:42PM -0700, R. Joseph Newton wrote: Guay Jean-Sébastien wrote: my $errors = 0; open (CRITICALSERVERS, $crout) || $errors += 2; that will translate to: my $errors = 0; ( open (CRITICALSERVERS, $crout) || $errors ) += 2; Nope. $ perl -MO=Deparse,-p -e 'open (CRITICALSERVERS, $crout) || $errors += 2' Can't modify logical or (||) in addition (+) at -e line 1, at EOF -e had compilation errors. ((open(CRITICALSERVERS, $crout) || $errors) += 2); Thanks. I stand corrected. I'm afraid I am not very familiar with these pitfalls, because my coding style doesn't often bring me up against them. Usually, if I felt a need to consult precedence tables to be sure, I would just use explicit parentheses. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Regular expression question: non-greedy matches
Boris Shor wrote: Hello, Perl beginner here. I am having difficulty with a regular expression that uses non-greedy matches. Here is a sample code snippet: $test = Yea 123xrandomYea 456xdumdumNay 789xpop; while ($test =~ /Yea (.*?)x.*?(?:Nay (.*?)x)?/g) You have your non-capturing test in the wrong place. See below. { print $1\n; print $2\n; } The first problem is that you are not using strict or warnings: Greetings! E:\d_drive\perlStuffperl -w $test = Yea 123xrandomYea 456xdumdumNay 789xpop; while ($test =~ /Yea (.*?)x.*?(?:Nay (.*?)x)?/g) { print $1\n; print $2\n; } ^Z 123 Use of uninitialized value in concatenation (.) or string at - line 5. 456 Use of uninitialized value in concatenation (.) or string at - line 5. The idea is that every 'phrase' is delimited with an 'x' and there are random letters between phrases. Well, there seems top be more to what you want than that. You seem to want clauses that begin with either Yay or Nay and are followed by a numerical expression. I expect to see: 123 456 789 I'm not sure what you are looking for here. But instead I get: 123 456 Why don't I get the second part of the regular expression? Does this work for you? Greetings! E:\d_drive\perlStuffperl -w -Mstrict my $test = Yea 123xrandomYea 456xdumdumNay 789xpop; while ($test =~ /(?:Yea|Nay)\s*(.*?)x/g) { print $1\n; } ^Z 123 456 789 Joseph -- 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 ref's of hash's
Mark Goland wrote: John, this code didn't work for me. Although I did have to change DATA to RD; What code? I see nothing above this to indicate what you are referring to. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Basic question
Kumar, Praveen (cahoot) wrote: Hello, Hi Praveen.K [Is that what your friends call you in conversation?] I am completely new to perl, and i am trying to write a small script, which based on the input given displays the value in an array. But when i try to execute the script i somehow fail saying Use of uninitialized value in concatenation (.) or string at ./pscr1 line 9, STDIN line 1. Well, since you are just starting out, it is very important to develop good habits right from the start. I am also enclosing the script, can some one let me know what is the problem with this. #!/usr/bin/perl -w use strict;# Always use warnings;# Until you know exactly why you are not using them. For now--always print This is your first program\n; @list=qw(good better best); is more readable as: @list = qw(good better best); $name=nobody; same as above print Please enter u'r name\n; The second-person possessive is correctly spelled your. Typos are one thing, intentional misspelling is very annoying to educated adults.. $name = STDIN; chomp ($name); print Hello $name\n; if ($name eq Tom) { print You are $list{$0}\n; Indent. Choose a number of spaces to use, then always indent the lines inside any block by that amount Let's try this again with meaningful formatting: if ($name eq Tom) { print You are $list[0]\n; }elsif ($name eq Dick) { print You are $list{1]\n; }elsif ($name eq Harry) { print You are $list[2]\n; }else { print nobodyi\n; } The other change I made above was to bring the elsif statements onto the same line as the closing brace. The difference is that, in the above, you can tell visually how the whole if/eslif/else structure executes together. One very good test is to look at the code from a distance where you can't actuall read it, and see if you can still tell what executes together. Bill already gave you part of the answer to your immediate question, but there is another problem, In your list element you say $list{$0}. That $0 variable has not been assigned. A number is just a number. It sound like you don't quite understand the difference between arrays and hashes. What are you using for reference materials on Perl? You really need to study at least a little of the language before you start writing. Imitation does not work very well. You have to know why each character in your code is there. I want to fill you in on a couple things that will make all your code easier to understand and debug. Perl is a language that can support a very natural style, but you have to use it.in a natural way to take advantage of it. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Using $_ in a function if no argument is passed
JupiterHost.Net wrote: Hello List, It just occurred to me that many Perl functions use $_ if not other value is supplied. chomp for instance..., which is very handy... Yes. Like the peaceful feeling that comes the first time one shoots up junk. If one wanted to write a function that used either the given argument or $_ how would you do that? Don't myfunc($myvalue); or myfunc; #uses the current value of $_ sub myfunc { my $func_arg = shift || 'some constant default value'; # you wouldn't just do '|| $_;' would you? If you are going to use a construct like the above, you should have a constant default value. The loop variable $_ is for loop, not functions Be careful about what you ask for. While there is a good use for both the loop variable $_ and default values for certain cases where there may or may not be an argument offered, both approaches also present some serious dangers. It is much better to explicitly pass arguments. Dependency on magic effects can make your code very fragile and very hard to debug. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Using $_ in a function if no argument is passed
Paul Johnson wrote: $_ = Leave me alone!; $s = 0; Better yet: $lower_or-mixed_case_string = 'o'; to_upper $lower_or-mixed_case_string; With intelligent use of the editing facilities available, extra characters do not cost much. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: New to Perl
John W. Krahn wrote: 1 or greater -1 or less A pox on both your houses: ;-o) Greetings! E:\d_drive\perlStuffperl -w my $test = .1; print (($test ? $test : 'false'), \n); ^Z 1e-005 Greetings! E:\d_drive\perlStuffperl -w my $test = -.1; print (($test ? $test : 'false'), \n); ^Z -1e-005 How about just non-zero? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: New to Perl
Oliver Schnarchendorf wrote: On Fri, 2 Apr 2004 12:19:32 -0800 , Bajaria, Praful wrote: However, when I print print content $request-content \n; I get content HTTP::Request=HASH(0x8546b3c)-content and print $response-message \n; give me message HTTP::Response=HASH(0x8546b60)-message Am I doing something wrong here ? Yes... but unknowingly. You are trying to print what a hash function returns ($hash-function). The problem is that perl doesn't see it this way. It will just print the data type of the hash variable (HASH(0x000)) and see everything following the hash variable (-function) as normal text. That too, perhaps. In more general terms, function calls are not interpolated within strings. There are a few ways around this. The easiest two for you are (a) Store the value returned by the hash-function in another variable before you use it: my $content = $request-content; print content: $content\n; (b) Use the perl way of concatenating strings with '.''s: print content: .$request-content.\n; Option (b) above is generally my approach for function calls. So far its been very dependable. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Timezone conversion
Distribution Lists wrote: can someone give me ideas of how I could covert this date and time stamp that is in GMT to Central time ? 2004-04-01-19:15:15.525+00:00 Thanks Yes. You can. Look at a map of time zones, or check the offest on any message that is dataed by central time, and correct the hours figure by the amount specified. BTW--humans, who have names, get much more ready responses than phantoms and trolls, who do not. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Is this possible? (file handles)
Jeff Westman wrote: This doesn't answer my question. Okay I wanted to know if it is possible to remove a file using the FH name, not the variable name referencing it. No. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Execute include and return variables
Alok Bhatt wrote: Hi all: Hi Tomas, I cannot include a file so it can return all the variables I assigned. #FILE1.pl $var1= tom; #FILE2.pl do FILE1.pl #open $prog,'FILE1.pl' or die $!, #use 'FILE1.pl' #import 'FILE1.pl' In FIle2: do FILE1.pl (use double quotes) If you want to use use , rename to file1.pm and use use file1, instead of use file1.pm. Hope that helps. :-) Alok There is a larger conceptual issue here. I think the OP is starting out on the wrong track with this approach. Declaring variables in remote files is just not a good idea. Perl has evolved, and evolved much better ways to handle containment. I would ask what purpose is he trying to achieve by doing this.Generally, when people declare variables in included files, they are trying to create global variables. I think it is better to steer him towards safer ways of sharing data between parts of a program. Besides, double quotes are not neccesary: rags.pl: #!perl -w $badly_named_variable = 5; Greetings! E:\d_drive\perlStuffperl do 'rags.pl'; print $badly_named_variable\n; ^Z 5 Though you could not get away with junk like this using strict. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Execute include and return variables
Tomas Corral wrote: Hi all: Hi Tomas, Please start a new message to the group when you have a new subject. Your message was lost in a thread concerning Network Shiffer Modules. I cannot include a file so it can return all the variables I assigned. #FILE1.pl $var1= tom; #FILE2.pl do FILE1.pl #open $prog,'FILE1.pl' or die $!, #use 'FILE1.pl' #import 'FILE1.pl' print(var1=$var1); I hanged arround perldoc perlfunc and google and... I guess I need help Don't do this. This is not a productive use for your efforts. If you explain why you would want to declare a variable in some other file, we can point you toward better ways to accomplish your purpose. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: What is happening here
WC -Sx- Jones wrote: WC -Sx- Jones wrote: What is happening here - while(1) { (++$count) ? $count += $count-- : $count += $count++; :) May I ask a different way? #! /usr/bin/perl use strict; use warnings; my $count; my $str; while(1) { (++$count) ? $count += $count-- : $count += $count++; $str = unpack(B32, pack(N, $count)); print $count \tis binary $str\n; exit if $count 60_000; sleep 1; } __END__ -Sx- PS - I am admit that I am likely in the middle of a nervous break-down LOL :) BTW - Joseph was correct about the side-effects issue. :) No one seemed to address the other data formats... That is pretty much how I got there. Not that I would have to unpcak those numbers--they're pretty much engreained onmy memory ever since an instructor gave us the prefect number problem as an assignment. Definitely increased my admiration for Euclid, who did not have the binary p[aradigm to work with. To elaborate a little: Greetings! E:\d_drive\perlStuffperl -w #!perl -w use strict; use warnings; my $count; while(1) { if (++$count) { # on second round: $count == ($oringinal * 4 - 1) + 1 == $oringinal * 4 # $oringinal = $count == 1 $count += $count; # $count == $oringinal * 2 $count--; # $count == ($oringinal * 2) - 1 my $alternative_yes = $count; #dead code $count += $count; # $count == (($oringinal * 2) - 1) * 2 == (($oringinal * 2) * 2) - (1 * 2) == ($oringinal * 4) - 2 $count++; # $count == (($oringinal * 4) - 2) + 1 == $oringinal * 4 - 1 my $alternative_no = $count; #dead code } else { die The impossible has happened! $!; } print $count\n; exit if $count 60_000; sleep 1; } ^Z 3 15 63 So the upshot is that the function essentially quadruples the base value for the loop on each iteration, but prints a value one less than the base value. The values above could be clearly exzpressed as 4 -1 16 -1 64 -1 256 -1 or 4 ** 1 - 1 4 ** 2 - 1 4 ** 3 -1 ..with a bit of sleight of hand thrown in for spice. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: What is happening here
Jeff 'japhy' Pinyan wrote: On Mar 30, WC -Sx- Jones said: my $count; while(1) { (++$count) ? $count += $count-- : $count += $count++; print $count\n; exit if $count 60_000; sleep 1; } The main problem is the PRECEDENCE. Your ? : line is run like so: ((++$count) ? ($count += $count--) : $count) += $count++; Have you tested this? I don't see the precedence issue happening here. Could you try duplicating these reults with code explicitly specifying the precedence you show? I do not think you are going to find that the outer parentheses you show represent the actual precedence. Remember that the ? and : are not different operators, but different parts of the same operator. If the += operator has a higher precedence than ?, it will also have a higher precedence than :. Joseph -- 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 Problems
Nigel Peck - MIS Web Design wrote: Hi all, I'm sure I'm just being stupid here but I can't see where: I have an array of hash references that I'm trying to sort by one of the key/value pairs in the hashes (see code below). I get various errors, the current one being: Can't coerce array into hash at /web/secure.miswebdesign.com.on-water/cgi-bin/manager.pl line 2392. Line 2392 is the line where the sortfunc function is defined. Thanks in advance for much needed help :) Cheers, Nigel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= my @boat_list; foreach my $boat ( $boats-findnodes(//boat) ){ my $section; foreach my $ab ( $boat-findnodes(section) ) { ($section = $ab) if ($ab-getAttribute(title) eq General Details); } my $boat_details = {}; $boat_details-{num} = $boat-getAttribute(num); $boat_details-{name} = $section-findnodes(name)-[0]-firstChild-data; $boat_details-{type} = $boat_type-getAttribute(title); $boat_details-{price} = $section-findnodes(price)-[0]-firstChild-data; push @boat_list, $boat_details; } sub sortfunc { $a-{name} cmp $b-{name}; } my @sorted_boats = sort sortfunc @boat_list; Try my @sorted_boats = sort {sortfunc($a, $b)} @boat_list; Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Incrementing count
[EMAIL PROTECTED] wrote: I'm sorry, the previous subject should have been changed. My apologies. while (FILE) { $counter++; } I know this is probably simple, but how would I increment by 20? In other words, $counter would increment 1 time for every twenty lines of the file? Any help would be appreciated. You probably need two counters then--one outside the loop, and one inside. There is a Perl variable that representsthe loop counter also, but you might as well be explicit, since your focus seems to be on the loop count. Can you tell us what your overall purose is? That would give us a much better idea of what advice to give. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Incrementing count
Smoot Carl-Mitchell wrote: This is not what the poster asked. Actually, yes it is, at least part of it. He said would I increment by 20?... $counter would increment 1 time for every twenty lines of the file? This will increment the counter by 20 for every line of the file. Read without re-interpretation, this indicates precisely to increment once, by 20, for each 20 lines. Something like this does what the original poster wants: Perhaps, but is it what he asked for. I think it does a disservice to students to silently fill in the gaps in their logic. You can give them the right answer to a particular problem, but still leave them without an awareness of the need to be precise in their specification. while (FILE) { $counter++ if ! ($. % 20); } This increments the counter by one for every 20 lines of input. $. is the input line counter. % is the modulo operator. See perlvar for the details on $. and perlop for the modulo operator. -- Smoot Carl-Mitchell That does help, presuming that the OP had actually misstated his desired results. The closest I can come to the desired results as expressed [since I don't much like the cryptic $. built-in] is my $counter = 0; my $inner_counter = 0; while (FILE) { $inner_counter++; $counter +=20 unless $inner_counter % 20; } Which seems pretty damned pointless to me, but is what the OP asked for. Better that we guide him towards the practice of carefully defining his problem. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: `next LABEL' usage
Harry Putnam wrote: Charles K. Clarkson [EMAIL PROTECTED] writes: HTH, Definitely and thanks for the examples. I think I was making this more complicated that it needed to be. It's slowly sinking in what all a `return' can do. Hi Harry, Glad Charles got you squared away. I have to say it again, though--you will make much more progress by focusing on a plain-language description of what you are trying to accomplish, than by thinking in code. Or, if you must express your ideas directly in code, run them in the command line compiler first, to get the immediately available sanity check, before posting. The problem with saying I want to do something like this... then showing guesswork code, is that the code you showed already does whatever it does, or nothing at all if sytax errors preclude compilation. How do we know, by looking at code alone, whether the effect, if any, achieved by the code, is the effect desired? Did you notice how quickly the issue resolved once Charles figured out what you wanted--in words? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: File content question
Sagar, Sanjeev wrote: Big Thanks ! My log file looks like below Would be better with multiple sections, and only a few representative line per... 2004-03-26 @ 00:00:01 [EMAIL PROTECTED] -- 10881 10864 hyb01 :INFORMATIONAL ... Script/function sql_instance_ping_final started at Fri Mar 26 00:00:04 CST 2004 -- seconds -- 4:INFORMATIONAL Any idea on reseting %datastore will be highly appreciable. Yes it will take an appreicable effort to come up with any ideas. What do you want this script to do for you? Do you want to have all the log information in memory so that you can compare between checks? In that case you will probably want a ahs of hash references. The keys of the outer hash would probably be the times of the checks The value for each key would be a reference to an anonymous hash containing all of the status keys and their values for a given checktime. You can make use of the file structure in deciding when to add one set of status vlues to your ahs and start the next. You know that: Each check-time record starts with a series of lines, each of which starts with a specifically formatted date and time string. The end of the report is marked by a constant string; Variable_name Value This constant string is followed by the name-value pairs you seek to organize. So clearly, the first date formatted string you encounter on each timecheck should signal you to store the previous anonymous hash, and to get the date information that will be the key of the next. Depending on whether you are making use of the information contained in the header lines, you will process them or not while watching for the constant string /^Variable_name Value$/ which will signal your program to start collecting the key-value pairs for the current time-check. Joseph Somthing like this: Greetings! E:\d_drive\perlStuffperl -w my %time_checks; my $line = DATA; while ($line) { my $current_time; if ($line =~ /^(\d{4}-\d{2}-\d{2} \@ \d{2}:\d{2}:\d{2})/) { $current_time = $1; } $line = DATA until $line =~ /^Variable_name Value$/; my $current_values = {}; $line = DATA; until ($line =~ /^(\d{4}-\d{2}-\d{2} \@ \d{2}:\d{2}:\d{2})/) { chomp $line; last unless $line; my ($key, $value) = split /\s+/, $line; $current_values-{$key} = $value; $line = DATA; } $time_checks{$current_time} = $current_values; chomp $line; } foreach $time_check (sort keys %time_checks) { print \n\n$time_check:\n; my $check_values = $time_checks{$time_check}; print$_: $check_values-{$_}\n foreach (keys %$check_values); } __DATA__ 2004-03-26 @ 00:00:01 [EMAIL PROTECTED] -- 10881 10864 hyb01 :INFORMATIONAL 2004-03-26 @ 00:00:01 [EMAIL PROTECTED] -- 10881 10864 hyb01 Function (up) returned (0) return code. -- seconds -- 1:INFORMATIONAL Variable_name Value Aborted_clients 5592 Aborted_connects4 Bytes_received 500 Bytes_sent 5000 Com_admin_commands 0 Com_alter_table 27 Com_analyze 0 Com_backup_table0 2004-03-26 @ 00:15:01 [EMAIL PROTECTED] -- 10881 10864 hyb01 :INFORMATIONAL 2004-03-26 @ 00:15:01 [EMAIL PROTECTED] -- 10881 10864 hyb01 Function (up) returned (0) return code. -- seconds -- 1:INFORMATIONAL Variable_name Value Aborted_clients 5592 Aborted_connects4 Bytes_received 2678 Bytes_sent 6935 Com_admin_commands 0 Com_alter_table 29 Com_analyze 0 Com_backup_table0 2004-03-26 @ 00:30:01 [EMAIL PROTECTED] -- 10881 10864 hyb01 :INFORMATIONAL 2004-03-26 @ 00:30:01 [EMAIL PROTECTED] -- 10881 10864 hyb01 Function (up) returned (0) return code. -- seconds -- 1:INFORMATIONAL Variable_name Value Aborted_clients 5592 Aborted_connects4 Bytes_received 6023 Bytes_sent 10001 Com_admin_commands 0 Com_alter_table 15 Com_analyze 0 Com_backup_table0 2004-03-26 @ 00:00:01: Bytes_received: 500 Com_analyze: 0 Bytes_sent: 5000 Com_alter_table: 27 Com_backup_table: 0 Com_admin_commands: 0 Aborted_clients: 5592 Aborted_connects: 4 2004-03-26 @ 00:15:01: Bytes_received: 2678 Com_analyze: 0 Bytes_sent: 6935 Com_alter_table: 29 Com_backup_table: 0 Com_admin_commands: 0 Aborted_clients: 5592 Aborted_connects: 4 2004-03-26 @ 00:30:01: Bytes_received: 6023 Com_analyze: 0 Bytes_sent: 10001 Com_alter_table: 15 Com_backup_table: 0 Com_admin_commands: 0 Aborted_clients: 5592 Aborted_connects: 4 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Incrementing count
Smoot Carl-Mitchell wrote: Hi Carl-Mitchell, Please stay on the list. I will address that. I'll take this offline, since I do not think it should be on the list I disagree. With all due respect, you and I have not developed a personal correspondence. There are some very good reasons for the custom of keeping our discussions on-list. Perhaps, but is it what he asked for. I think it does a disservice to students to silently fill in the gaps in their logic. You can give them the right answer to a particular problem, but still leave them without an awareness of the need to be precise in their specification. I do not think it is a disservice. I thought the specifications were very clear. I think you were mistaken in your interpretation and I was pointing it out. I have no problem being corrected when I am wrong. And we can certainly discuss offline our diagreement and whether I am doing a disservice to students. No. The subject of learning itself, the learning process, and what helps or hinders or helps the learning process, is a discussion that students using the list as a resource should be aware of. It is not meant as a comment on any person, but on a need for care in specification very particular to the task of learning to program. I do not think I was. Can you elaborate on what you mean by disservice. That is fine, although it was not me you were responding to in the post to which I responded. I suspect you are right about the actual intent. All I can tell you is that I have watched a lot of traffic on this list, and I have seen a lot of floundering where people have too quickly re-interpreted a specification. Mu interpretation of the OP requirments was something like processing an input file with 20 lines per entry and counting the entries. That is a fairly practical problem. Agreed. Smoot Carl-Mitchell I am sorry if you take any personal offense here. No offense was intended, only discussion. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: What is happening here
Andrew Gaffney wrote: WC -Sx- Jones wrote: What is happening here - #! /usr/bin/perl use strict; use warnings; my $count; while(1) { (++$count) ? $count += $count-- : $count += $count++; print $count\n; exit if $count 60_000; sleep 1; } __END__ -Sx- That is a damn good question. I'm not sure what results I was expecting when I ran it, but it sure wasn't this: 3 15 63 255 1023 4095 16383 65535 I'm stumped, also.I would have expected progressive 2**n -1 As far as I can tell, the test in the conditional operation should always evaluate true. The preccedence of += and postfix decrement should have decremented after the value had doubled. After printing, the number should be re-incremented Sheesh--there no damn short-circuit on the evaluation!! Well, I'll be darned! Only one of the two alternatives will be assigned, but both are evaluated. That is why the following did not produce the same effects: Greetings! E:\d_drive\perlStuffperl -w use strict; use warnings; my $count; $count++; while ($count = 6) { $count = $count * 2 - 1; $count = $count * print $count\n; next unless $count = 65534; $count++; sleep 1; } ^Z 1 3 7 15 31 ... So--- Greetings! E:\d_drive\perlStuffperl -w use strict; use warnings; my $count; while(1) { if (++$count) { $count += $count; $count--; my $alternative_yes = $count; $count += $count; $count++; my $alternative_no = $count; } else { die The impossible has happened! $!; } print $count\n; exit if $count 60_000; sleep 1; } ^Z 3 15 63 255 1023 4095 16383 65535 Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: What is happening here
R. Joseph Newton wrote: Andrew Gaffney wrote: WC -Sx- Jones wrote: What is happening here - That is a damn good question. I'm not sure what results I was expecting when I ran it, but it sure wasn't this: 3 15 63 255 I'm stumped, also.I would have expected progressive 2**n -1 As far as I can tell, the test in the conditional operation should always evaluate true. The preccedence of += and postfix decrement should have decremented after the value had doubled. After printing, the number should be re-incremented Sheesh--there no damn short-circuit on the evaluation!! Well, I'll be darned! Only one of the two alternatives will be assigned, but both are evaluated. ... It really is an object lesson in the dangers of using lvalued functions in void context, for their side effects. The conditional operator is meant to return one of its alternative values. Unlike the or and and operators, though, it does not short-circuit its evaluation. It seems to evaluate the expressions for both alternatives, and then assign one or the other depending on the value of the test. Since the conditiional operator is used in void context, there is no lvalue to receive the primary product of the operation. The side effects here are the whoe show. while(1) { if (++$count) { $count += $count; $count--; my $alternative_yes = $count; $count += $count; $count++; my $alternative_no = $count; } else { die The impossible has happened! $!; } print $count\n; exit if $count 60_000; sleep 1; } Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: What is happening here
Tim Johnson wrote: Apparently (++$count) evaluates to 0, but I can't figure out why. Nope. Always true. It just doesn'yt matter. Bill sorta threw us a red herring here. Seeing the conditiional operator distracts your attention to thinking about the product of the conditional, which is not even used here. What does happen is that both alternative expressions get evaluated before the appropriate one is assigned [to The Void in this case]. It's all byproduct. So the second expression is evaluated first. Nope. They are evaluated in order. From there it's pretty self-explanatory. (++$count) will always evaluate to TRUE, since it will only get higher, and the first expression is evaluated. Maybe someone can enlighten us to some of the lesser known properties of the -- and ++ operators? It's definitely counterintuitive. Not at all. The only counter intuitive thing here is the lack of short-circuit in the evaluation of alternative values within the conditional. Now we know. As to the prefix [++$var, --$var] and postfix [$var++, $var--] operators, that also is pretty intuitive once you get connected with it. If the increment operator precedes the variable name, it means increment the variable then use its value. If the increment operator ifollows the identifier, it means Use the current value, then increment the variable. Very intuitive. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: warn ?!
Randy W. Sims wrote: #!/usr/bin/perl package NumStr; This makes sense to me. As a package, it makes sense to have overloaded operations. This is why I was asking if the value was really stored as a number. use strict; ... printf(as number = '%d', as string = '%s'\n, $ns, $ns); __END__ You can simulate more closely with XS: #include EXTERN.h #include perl.h #include XSUB.h Looks interesting, but I am not really familiar enough with XS to know what to make of it. I'll look at it again when I've had some time to check out the XS libraries. Joseph -- 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 math
Andrew Gaffney wrote: My code ended up looking like: use strict; use warnings; use constant PAY_PERIOD_DAYS = 14; my @payperiods; Underscores are both permissible and advisable in variable names: my @pay_periods; my @finalpayperiods; my $lastperiodend = Date::Simple-new('2004-01-10'); while() { my $newstart = $lastperiodend + 1; Good enough. $new_start should take the value following $last_period_end. my $newend = $newstart + 13; This works, but could be more clear. The number 13 here is sort of a magic number, which requires reading contextual code to understand. Better to use the size of the pay period my $new_end = $last_period_end + 14; or my $new_end = $last_period_end + PAY_PERIOD_DAYS; my @lt = localtime; last if(Date::Simple-new($lt[5]+1900, $lt[4]+1, $lt[3]) $newstart); This probably does what you want, but what does it mean? It may seem strange to say this about a single line, but I think this should be in a function of its own, if only so that it has a logiacl identifier. Hmmm, actually, this probably should not be inside the loop at all. Unless you expect some significant change in the local time values between iterations of the loop, you should perform the creation of the new Date::Simple object only once, then compare the object as you go through the loop. Better yet, you should have this in the loop control, since controlling the execution of the loop is its purpose. while($last_period_end $current_date - 1) { push @payperiods, $newstart to $newend; $lastperiodend = $newend; } my $periodcounter = 0; =item remove complicated stuff foreach(reverse @payperiods) { $periodcounter++; last if($periodcounter 6); push @finalpayperiods, $_; } =cut for (1..6) { push @final_pay_periods, pop @pay_periods; } Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: warn ?!
James Edward Gray II wrote: On Mar 27, 2004, at 12:10 AM, R. Joseph Newton wrote: Not exactly. It is not the newline \n that would give the full output of the warn function, but the $! variable, which contains the most recent warning or error message. I believe you are confusing two often paired, but not otherwise related features of Perl. Actually, I was starting to think that I had misstated the above, by saying output of the warn function, but I think I was closer to the mark. You can print $! and get the error message, but the line information is the product of warn or die: open IN, 'some_nonexistent_filename' or print $!; ^Z Name main::IN used only once: possible typo at - line 1. # built-in compiler warning No such file or directory # simply printing $! open IN, 'some_nonexistent_filename' or warn $!; ^Z .. No such file or directory at - line 1. warn() is a tool for delivering non-fatal error messages. It behaves differently depending if the provided message does or doesn't end in a newline character, as has been discussed in this thread. $! is a Perl interface to C's errno variable. It is set by failed system/library calls. While it may often be useful to issue a warn()ing including $!, it is by no means required. In this case, James, it is what the OP was looking for. He specifically saw a problem with having the warning message come out as a simple print statement. I'm not terribly concerned about the internal mplementation. I am speaking of the effect. Unless I am missing something about what the OP wnated here. It may be useful to issue warn()ings including many variables. $@ is a common example, in fact, it's the default message warn() will display if not provided one. You may want to use your own variables, so simply print a message in your own words about what happened. That's what warn() is for. I agree, which is why I tend to recommend the darn-near canonical form I showed. Interestingly enough, it is almost the same generalized warning produced by $@: Greetings! E:\d_drive\perlStuff\hdrperl -w open IN, 'some_nonexistent_filename' or warn $@; ^Z Name main::IN used only once: possible typo at - line 1. Warning: something's wrong at - line 1. except that the $@ adds the Warning: prefix. It seems pretty clear to me, that although modular in their function, these Perl built-in variables were precisely designed to work with the warn and die functions. I'll hold with my essential point--that you get a lot more useful information out of your warning by havng the $! at the end of your custom message. I would recommend always using such custom messages also, and putting design thought into them. That is why I suggested having them include the name of the function containing them, and why I generally specify the operation being attempted. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
Randy W. Sims wrote: On 3/27/2004 2:23 AM, R. Joseph Newton wrote: These lines should probably be going into a hash, keyed to the portion of the line before the colon. Don't forget that some header fields can appear more than once. Regards, Randy. Actually, I'm pretty sure it is only the Received header that would ever show more than once in the main header of a message. [Content-type and related part-specific lines might show up more than once, but only once per part.] That would take some special handling. I think the factor to put to use for Received headers specifically is that their ordering is consistent. So each Received line encountered should be pushed into an array, perhaps. Then the lines could be popped to retrace the route from origin to destination. So it is not quite that simple. Still, it is not inordinately complicated either. Good design, with small, well-designed subroutines, should make it fairly straightforward. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
Harry Putnam wrote: Something like: [...] snipped getopts and other unrelated stuff while(FILE){ chomp; my $line = $_; Why here. Since you are doing this with each line, you could write in the loop control: while (my $line = FILE) { Not sure I understand the advantage. In my formulation, `$line' is minus the trailing newline... which I've found to be nearly always a plus. Different question. Sorry, that was sloppy of me, but this still can be handled with more clarity by declaring the loop control variable in the loop control. while (my $line = FILE) { chomp $line; The chomp should indeed have been there, but it is generally better when the statement tells you what is being chomped. Defaulted function calls are pretty much the [Daddy] Bushisms of programming. They are not really complete statements, but the listener [Perl] is expected to fill in the gaps in logic. ## @hdregs is an array of several regex for the headers for($ii=0;$ii=$#hdregs;$ii++){ Why no space between clauses? Why no space around assignment operators? Just how I've become accustomed to writing code. Probably not a good plan for when others need to read and revise it. For yourself too, I would hope. Why a C-style for loop? Are you using the index somewhere? Well yes, sort of. I wanted a way to ensure that each reg has hit at least once. Otherwise we don't print. So I used a formulation like this (Not posted previously for clarity): if ($data{$hdregs[$ii]}++ == 0) { ## it will only be 0 once $hdelem_hit_cnt++; } You probably need a hash if what you are looking for is uniqueness. They are indeally designed for elements that must remain unique Then before printing we compare $hdelem_hit_cnt to ($#hdregs + 1): I hate to say it, but I have to break here. Hint--when you create an identifier, pronounce the identifier aloud, once. Then say it real fast, ten times. If you start to gag, choose an identifier that you can pronounce aloud. Okay, I took a deep breath, now. I think I can trudge onward. It doesn't need to be a trudge, though--that's what bugs me. sub test_hdr_good { if ($hdelem_hit_cnt == ($#hdregs + 1)) { $test_hdr_good = TRUE; $hdelem_hit_cnt = 0; } } They should be the same if all regs have hit at least once. If not the same... we don't print. Don't count on any predetermined set of headers being hit. There are very few headers that appear in each and every message. At a time when I had 13, 038 message in a given mailbox, these were the only header items to appear in exactly that many messages: Date: 13139 X-Mozilla-Status: 13139 X-UIDL: 13139 From: 13139 X-Mozilla-Status2: 13139 Subject: 13139 though Received: 83781, Delivered-To: 20954, X-SMTPD: 16868 may also have appeared in all. I would suggest that rather than counting hits, you simply be prepared to handle undefs or empty strings if a header line of interest is not present. There simply are not eneough signifant header tags duplicated to have this aspect of the problem dominate your overall strategy. If you have a particular interest in the transmission path, then maybe it is worth the extra effort. Sorting headers for a searchable archive does not require that great a focus. if($line =~ /$hdregs[$ii]/){ Right now, you have just gotten quite a bit of information about this line, including [with the same amount of effort, the type of header line involved. ## Capture the line push @hits,$line; You now have thrown away the type information for the line, by throwing it back in an usorted bag. As Joe Ben Stamper said When you fall, fall in the direction of your work. These lines should probably be going into a hash, keyed to the portion of the line before the colon. You may wish to throw out about 3/4 of them, since there are hundreds of different attributes carried in header lines, and only a small subset is going to be useful for data management. Under any circumstances, you should probably try to capture *all* the information available at this point. I'm not following you here. The code does capture the entire line. Is that what you want? It seems to me that a line of text is much less informative and programmatically useful than a key-value pair in a hash. The value for Received lines should be an array, though, probably. And using Randy's concatenation technique, including folded lines (concat'ed) Prior to printing the array is sorted like this: for(sort @hits){ print... } So that the ouput has some sort of uniformity. Further, if I key a hash with stuff before colon, repeated hits like on `Received' lines will disappear into the ether. Yes, you will have to watch for the Received lines for special handling. The other main header lines will be
Re: Home made mail news search tool, and folded header lines
Charles K. Clarkson wrote: Harry Putnam [EMAIL PROTECTED] wrote: : : R. Joseph Newton [EMAIL PROTECTED] writes: : : Something like: : [...] snipped getopts and other unrelated stuff : while(FILE){ : chomp; : my $line = $_; : : Why here. Since you are doing this with each line, : you could write in the loop control: : while (my $line = FILE) { : : Not sure I understand the advantage. In my : formulation, `$line' is minus the trailing newline... : which I've found to be nearly always a plus. I think Joseph was implying the 'chomp'. This is still shorter and IMO clearer than using $_. Not exactly. Just being sloppy about it. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
Harry Putnam wrote: I think Joseph was implying the 'chomp'. This is still shorter and IMO clearer than using $_. while ( my $line = FILE ) { chomp $line; I hope it doesn't sound like I'm being a hard head... because at my stage of skill I'm not likely to stand on my practices as better than some other... but, I'm having trouble seeing what is shorter or better about this. Both have 7 entries to type. Keystroke counting is a relic of old tecnical limitations. I would never make it a major concern. And as for clarity, is it because you say `chomp $line' so it is apparent what is being chomped? Yes, yes, yes. The point is clarity. Having the declaration right there in the loop control communicates very boldly that this loop primarily processes lines being read. It may be implicit anyway, but since you have a named variable, why not declare it where it communicates most? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
Harry Putnam wrote: ... I'm having trouble seeing what is shorter or better about this. : sub test_hdr_good { I count 13 characters in test_hdr_good header_is_good { has 15 characters. For the price of two characters, you can = indicate the type of information [boolean] returned. If this does more than test and return true false, then the name shoudl probably be more like process_header(). = Avoid any ambiguity in the expansion of hdr = Generally, be more kind to yourself and others reading your code. = Have a function name you can call in a natural language syntax: if (header_in _short_list($line)) { add_to_simple_header($line, $message_outstream); ... } [Ooops--you can call fudgies on me, since I slipped in a few extra characters here. Sorry, my programming language of preference is English] Joseph -- 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 AoA
N, Guruguhan (GEAE, Foreign National, EACOE) wrote: [Implementation stuff snipped] Can some one tell me how do I this? Well, if you tellus what you want as output, we could maybe start. Hint--if you really have production code with variable names like @array1, @array2, etc., the best thing to do is trash it. It is highly unlikely to contain anything of value that cannot be easily replaced. Joseph -- 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 AoA [was the subject]
WC -Sx- Jones wrote: John W. Krahn wrote: replying) so James can take ownership of those parts of this thread. Not under most country's copyright laws he can't. :-( LOL :) I'd like to see that erroneous verbage - as words, expressed as thoughts and ideas in the discourse of conversation (whether spoken or written), cannot be copyrighted. Hooboy!! ...and this is all about Ways of structuring multi-dimensional data? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
R. Joseph Newton wrote: Ooops ... At a time when I had 13, 038 message in a given mailbox, should be ... At a time when I had 13, 1398 message in a given mailbox, Which makes the following more meaningful: these were the only header items to appear in exactly that many messages: Date: 13139 X-Mozilla-Status: 13139 X-UIDL: 13139 From: 13139 X-Mozilla-Status2: 13139 Subject: 13139 though Received: 83781, Delivered-To: 20954, X-SMTPD: 16868 may also have appeared in all. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
Harry Putnam wrote: Yes, I see now. I think I may not have understood the meaning of `global'. I understood it to mean these variables could theoretically be exported as in the case of `do ./this_script; from another script. I was under the impression that a `my($var);' at the beginning of`this_script' would prevent that... but without testing this, I'm guessing I may have it wrong. The point here is that the script itelf is too broad a scope for most variables. With a few exceptions, it is best when you can see the entire scope of any variable within a single screen. This takes structure. It is very much worth the effort, for the manageablity gained. Keeping your functions short, focused, and well-named will bear great rewards in handling any large0scale process. How is your work with references going? Have you practiced much in passing arguments by reference? Have you gotten to a good compfort level using them? If you want to do serious programming, you will have to do so. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
Smoot Carl-Mitchell wrote: Actually, I'm pretty sure it is only the Received header that would ever show more than once in the main header of a message. Read the relevant RFCs for mail message standards. I'd start with RFC2822 and work forward from there. This is definitely a good idea for anyone writing a full-scale mail handler There are a number of header fields which can legally appear more than once in a message I don't doubt that. I am going on what I have actually observed in some fairly extensives sequential archives of mail-as-received. I did produce a quite successful arcive storage, retrieval and search system without dealing with duplicate header lines. A full-scale mailer would probably be much more complicated. Presumably, one step to simplify the task somewhat would be to sort possible hear lines into broad grouoings that can be handled in uniform manner, then sort out the special cases, as well. Most instances where I have seen multi-valued header fields are single lines with the value string delimited in ways specific to the type of header tag. They do take some pretty sensitive handling, and I do not mean to trivialize the task. . Most MTAs do not check the message headers in detail. They only deal with the envelope information. So it is easy to generate a technically illegal message. Also note that any header can be folded, although it is typically only the Received: headers which are routinely wrapped for readability. I'll do some more scanning through my hdr directory to see how many folded lines I actually see. Ooooh! I see The To line can also get folded. I think the trick that I showed for testing for initial space should work for that It is very clear that the input processing has to use some sort of $curent_tag and $current_value scoped outside the input loop to handle this., Headers like Received should indeed be pulled aside for special handling, but I do not think you will find that many in actual use. As usual when writing code against a protocol standard, be liberal in what you will accept as valid input. True, but for headers, a good filter helps a lot. There is a lot of extraneous material there. Joseph -- 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 of the Month Club (end Of MARCH Edition)
WC -Sx- Jones wrote: James Edward Gray II wrote: 1. You show a means of variable declaration that you say replaces my() when in fact it's equivalent to our(). 2. Your use of local() is scary at best. It looks like a step backwards in Perl history to me. local() is pretty misunderstood to begin with and I don't think we, of all people, should be adding to the problem. I guess I am think as a brick: #! /usr/bin/perl -T use strict; use warnings; my $outside = 5; Okay, you have hit on something here. Variables declared outside of any subroutine are indeed global to the script as a whole. They really do not do much to protect the varaiable. This is why it is a good idea to limit the number of variables declared outside of subroutines to a bare minimum. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: warn ?!
James Edward Gray II wrote: On Mar 27, 2004, at 1:32 PM, R. Joseph Newton wrote: It seems pretty clear to me, that although modular in their function, these Perl built-in variables were precisely designed to work with the warn and die functions. I'll hold with my essential point--that you get a lot more useful information out of your warning by havng the $! at the end of your custom message. You still sound pretty confused to me. ;) Fact: If the warn() message ends is a newline character, the line number is not appended. Fact: This has nothing to do with ANY variables, it is the way warn() is designed. I see. It does seem a bit quirky, though, to use whitespace in this way. I wasn't really aware of this oddity in the design of warn(). I guess it makes sense, somehow. It makes more sense, though, to just provide some context iformation, then get the more specific error or warning message ctained in the variable. Whatever the particular features that come and go with the choice of whitespace, it makes more sense to explicitly call for the information provided in $!. Fact: This is the original question of this thread and what most of the replies address. You might like to reread them at this point. Please run these two one liners, observing the differences in output, for a good example of this: Sorry, they are non-portable: reetings! E:\d_drive\perlStuffperl -e 'warn Test Warning' an't find string terminator ' anywhere before EOF at -e line 1. perl -e 'warn Test Warning' perl -e 'warn Test Warning\n' Hope that clears things up. James Got it. Nice point. Now back to business. You get a lot more information back by asking for information. Joseph -- 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 file name /filehandle as argument to a subroutine...
urvashi mishra wrote: hi; i am trying to take input from multiple files Various I/P files are specified at command line... What is an I/P file? Do you mean an input file? Can anyone tell me how to pass the file name to a routine that opens it for parsing the same function is to be called for all the I/P files... Code is: foreach my $file (@ARGV) { # if it's dead, strip it out pass1($file); display(); should be: pass1($file); display(); print \n 8next**\n; } and the function to be called is sub pass1 So you are passing one of something? What is this function meant to achieve? The name should clearly indicate that. { my ($file)[EMAIL PROTECTED]; could be: my $file = shift; or my $file = $_[0]; though the form you chose makes sense if you expect later to expand the argument list. print $file; open(MIBFH,$file)|| die Error opening the $file $!\n; Better not to use the newline at the end. You get more information if you just: open(MIBFH,$file) or die Error opening the $file$!; Perl will take care of adding a newline after the error message. while(my $line = MIBFH ) { } close(MIBFH); } Can anyone help me...! Probably, if you tell us what the problem is. You have told us some of what you want, and shown us the code, but you haven't told us what happens when you run it. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: warn ?!
Randy W. Sims wrote: James Edward Gray II wrote: Fact: This has nothing to do with ANY variables, it is the way warn() is designed. Trivia: Did you know that $! does NOT contain an error string. It contains the error *number*. The only reason you see a error sting is that it has an overloaded stringification operator that calls strerror() on the numeric value that it contains. # assuming the file 'foo' does not exist in current directory. perl -e 'open FOO,foo or print $!+0' = 2 perl -MPOSIX -e 'open FOO,foo;print strerror $!+0' = No such file or directory Randy. Cool. Somehow, though It seems {6 * 1 == 12 / 2}-ish. By the time the variable is effectively accessed, the text is there. Greetings! E:\d_drive\perlStuffperl open IN, 'some_nonexistent_filename' or print $!; ^Z No such file or directory What is intriguing to me in this is that an overloaded operator wouuld be attched to a variable. this sounds like it gets into prtions of Perl that I've never really delved into. Is $! actually sored as a number? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
Harry Putnam wrote: Its going very steady... That is, I've never used a reference... : ) What can I say? You've got to take the step, if you want to get there. You will have plenty of help. Until you get these basic structuring skills down you are severely limited in the scope of tasks that you can take on. Focus on mastering the basic concepts of using references, and paassing them in and out of subroutines as well as using them to build multi-dimensioal structures of arbitrary complexity. Mastering and internalizing an understanding of references, scoping, function calls, and object creation will open many doors. Joseph -- 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 file name /filehandle as argument to a subroutine...
R. Joseph Newton wrote: Better not to use the newline at the end. You get more information if you just: open(MIBFH,$file) or die Error opening the $file$!; Should be: open(MIBFH,$file) or die Error opening the $file: $!; Sorry, Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: warn ?!
Alok Bhatt wrote: Hi Jai, Hi Alok, Please don't top-post. Instead, follow the material you are responding to, and trim extraneous matter. But the waring message output line 37 is different(just behaves as print) from same kind of message at line 57. Any suggestions please.. regards, Jay ... 36 { 37 warn Not able to create reg_test_cols \n ; A similar question was posted just yesterday. The difference between between the two lines (37 and 57) is that the second line contains a space after \n. As pointed earlier, you can take take it as a debugging option (ie remove \n or add a space and perl prints out the line no. too) :-) Alok Bhatt Not exactly. It is not the newline \n that would give the full output of the warn function, but the $! variable, which contains the most recent warning or error message. It is pretty much the same as with die(). The problem was not space after the newline, but the presence of the newline. The $! variable should not be followed by anything. If left as the last element of the warn or die message, it will be unrolled to the line number in the program as well as the line number in the currently selected filehandle. warn Something went wrong in function_name(), while doing something dangerous: $!; Greetings! E:\d_drive\perlstuffperl -w open IN, 'some_nonexistent_filename' or warn Something went wrong in main(), . while doing something dangerous:\n $!; my $stuff = IN; print $stuff; ^Z Something went wrong in main(), while doing something dangerous: No such file or directory at - line 1. readline() on closed filehandle IN at - line 3. Use of uninitialized value in print at - line 4. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Home made mail news search tool, and folded header lines
Harry Putnam wrote: I'm writing a home boy mail/news search tool and wondered if there is a cononical way to handle folded or indented header lines. An example would be that I wanted to run a series of regex against each line of input (While in headers) grabing the matches into an array for printing. Something like: [...] snipped getopts and other unrelated stuff while(FILE){ chomp; my $line = $_; Why here. Since you are doing this with each line, you could write in the loop control: while (my $line = FILE) { ## @hdregs is an array of several regex for the headers for($ii=0;$ii=$#hdregs;$ii++){ Why a C-style for loop? Are you using the index somewhere? Why no space between clauses? Why no space around assignment operators? if($line =~ /$hdregs[$ii]/){ Right now, you have just gotten quite a bit of information about this line, including [with the same amount of effort, the type of header line involved. ## Capture the line push @hits,$line; You now have thrown away the type information for the line, by throwing it back in an usorted bag. As Joe Ben Stamper said When you fall, fall in the direction of your work. These lines should probably be going into a hash, keyed to the portion of the line before the colon. You may wish to throw out about 3/4 of them, since there are hundreds of different attributes carried in header lines, and only a small subset is going to be useful for data management. Under any circumstances, you should probably try to capture *all* the information available at this point. } } } (somewhere later... if some body regex also match print the hits.) I used a for loop so as to stop at each incoming line and compare it to a number of regex in rotation, instead of using a possibly long string of alternation operators (if ($_ =~ /regex|regex2|regex3/) etc But going this route means lines like `Received: ' lines that might have folded (indented) lines containing newlines after them will get missed. Then buffer the input. Declare a variable outside of the loop to hold the preivous line. If the line currently being read begins with whitespace, join it to the $current_line with a newline. It might take a little restructuring of the sequence within the loop. This is one case where a priming read could be of assistance, since your loop could then have something in the buffer to spit out unless the line being read has space at the start. It seems like it might take some fairly complex code to do something like above but include slurping the indented lines on hits that have them. I wondered if there is some well worn way to do this? I'm not sure about well-worn, but it doesn't have to be all that complicated either: Greetings! E:\d_drive\perlStuff\hdrperl -w use Data::Dumper; open IN, 'hdr6.txt' or die Couldn't open header file: $!; # stuff specific to storage on my mailer: my $current_line = IN; my $date_string; if ($current_line =~ /From - (.*)$/) { $date_string = $1; } # general purpose code for verbatim mail headers: $current_line = IN; my ($current_key, $current_value) = split /:\s+/, $current_line; my %header_info; while (my $line = IN) { if ($line =~ /^\s+/) { $line =~ s/^\s+/ /; $current_value .= $line; } else { $header_info{$current_key} = $current_value; ($current_key, $current_value) = split /:\s+/, $line; } } print Dumper(\%header_info); ^Z $VAR1 = { 'MIME-Version' = '1.0 ', 'Status' = '', 'X-Spam-Status' = 'No, hits=-100.1 required=5.0 tests=SUBJ_ENDS_IN_Q_ MARK,USER_IN_WHITELIST version=2.20 ', 'List-Post' = 'mailto:[EMAIL PROTECTED] ', 'X-Mailer' = 'Mozilla 4.79 [en] (Windows NT 5.0; U) ...' [about 10 or 15 more headers. You can now choose among the relevant ones] }; HTH Joseph -- 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 Help Needed !
[EMAIL PROTECTED] wrote: foreach my $response ($record-{keys %response_values} ) What is this? It looks like you are trying to use a list as a hash key. I don't think that is going to work. A hash element should take a scalar as its key, not a list: Greetings! C:\Documents and Settings\rjnewtonperl -w my %hash = (first = 'one thing', second = 'another', third = 'still another') ; foreach $try_a_key ($hash{keys %hash}) { print $try_a_key\n; } ^Z Use of uninitialized value in concatenation (.) or string at - line 3. There is one, sorta quirky, way that it can work, though: Greetings! C:\Documents and Settings\rjnewtonperl -w my %hash = (first = 'one thing', second = 'another', 3 = 'still another'); foreach $try_a_key ($hash{keys %hash}) { print $try_a_key\n; } ^Z still another Of course, in the above, the foreach is superfluous, since this syntax willalway put one or fewer items in the list. Is that what you were looking for--something keyed to the number of keys in a hash? Otherwise, you may have to go back and define your goal and steps to reach it more clearly. Joseph -- 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 Help Needed !
Normandin, Jason wrote: Hi I am scoping the %response_values hash at the top. I dont understand why it would need to be temporary as I am referancing that hash outside of the loop when I iterate through. I changed the syntax to referance the oids rather then the hash name and I get the following error: Can't use string (%response_values) as a HASH ref while strict refs in use at H:\nhsParseSnmpLog.pl line 72, SNMP_L OG chunk 78. Here is what I have: .. SNIP.. use strict; my (%request_hash,%response_hash); .. SNIP... elsif ( m/RESPONSE:/ ) { # my ($time,$timeSecs,$request_id,$ip_address,%response_values,$oid,$oid_value); Best not to do this. it is good that they are soped within the sub, but would be even better if you declare them at the time they are used, or just prior to their first use. # Set these local to each record my @lines = split/\n/; my %response_values; foreach my $line (@lines) { next if $line =~ m/REQUEST:/; my $timeSecs=$1 if $line =~ m/# Time (\d+)\.\d+ seconds/; my $time=convertUtcToLocaltime($timeSecs); my $request_id=$1 if $line =~ m/\[REQUEST_ID\] (\d+)/; my $oid=$1 if $line =~ m/\[OBJECT_ID \] (.+)/; my $oid_value =$1 if $line =~ m/[\[COUNTER \]|\[GAUGE \]|\[INT \]|\[TICKS \]] (.+)/; $response_values{$oid}=$oid_value; } push @{$response_hash{$request_id}},{time = $time,oids = %response_values}; } .. SNIP .. Just snip? If this is getting long enough that you need to ship, then it is getting too long to be in one sub. Start at the top again. What data do you have to work with, in what form? What kind of information do you want out of the process in what form? Unfortunately %response_hash is so genral as to say nothing about the meaning of the data in context. I have the feeling that, if you take a fresh look at the original problem with a view to what you have to work with, and what end result you want to achieve, we can help you find much more straightforward means to get there. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Playing with Unicode
James Edward Gray II wrote: Why when I run this one-liner: perl -e 'print \x{2660}\n' do I see this: Wide character in print at -e line 1. Makes sense. 2660 would overflow a one-byte character. I'm assuming that's a warning, since I still get the expected output, but why am I getting it, when I didn't ask for them? Is there a better way to drop in a unicode character? I think you need to warn the compiler ahead of time that you are reading or writig unicode. It adapts anyway, but it's just reminding you. You might see if you can make sense out of perldoc encoding perldoc perlunicode though they are both rather windy and circuituous. Joseph -- 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 conencting to oracle after upgrading to oracle 9i
Nilay Puri, Noida wrote: Hi All, On sparc m/c SUN OS 5.8 , I have recently upgraded from Oracle 8i to Oracle 9i. ANd I had DBD:Oracle 1.12 installed on it. Now the perl files give error : DBI-connect(hemdadev) failed: ERROR OCIEnvInit at test.pl line 18 And at line 17 I have : $dbh = DBI-connect(DBI:Oracle Is that DBI::Oracle, or DBD::Oracle? They probably are not interchangeable. My bet would be on DBD::Oracle. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $dbh-do('\@proc')
Jayakumar Rajagopal wrote: Hi all, I have to use PERL to run .sql files No you don't. When I was in Oracle class, nobody even knew what Perl was, and we ran scripts directly at the prompt. I think you are getting your interfaces mixed up here. Perl is called from a shell of the OS. The Oracle command interface is nopt a shell to the OS, but only to the Oracle SQL engine. You should consult your Oracle documentation for the specific syntax to use at the command line. Do not try to involve Perl in the task as you have structured it. Just call your SQL script. SQL start runstmts.sql; Don't confuse the two interfaces. You can run a script with Perl, using the DBI module and DBD::Oracle, but that will probably involve reading the script statements and executing them one-by-one. Unless there is a need to do this programatically, though, running the SQL script has nothing to do with Perl. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: returning hashes, and arrays
Stuart White wrote: Here's 25 lines of sample input: -- Spurs 94, Suns 82 4/29/2003 SBC Center, San Antonio, TX Officials: #16 Ted Bernhardt , #33 Sean Corbin , #15 Bennett Salvatore 1st Period ... (11:23) [SAN 2-0] Bowen Jump Shot: Made (2 PTS) Assist: Parker (1 AST) (11:10) [PHX] Marbury Jump Shot: Missed ... Looks like a major task of parsing here. More than that, it branches into AI, since it requires major sensitivity to contextual cues. The big picture is creating a box score. the categories are points, offensive rebounds, defensive ... I plan on getting to the end by writing small programs that parse the lines for the different categories. There is a better way. Writing separate programs requires shelling out to communicate between them. Very inflexible. I would recommend instead that you learn about the use of subroutines. As you take on complex tasks, you will benefit by writing compact, mofular subroutines to handle processes at any particular level of abstraction. To use subroutines well, you of course must be comfortable with the use of references. With these two tools available, you will be well-equipped to taake on object-oriented programming. I see this as the point where you would want to branch out to multi-file programming. I have the feeling that by the time you have a good solution to this problem, you may need to develop some representative objects, since it is not a trivial task. Then, I plan on putting them all together, either as includes C includes, Perl uses into one main, No main in Perl, unless you define and explicitly call it. or cutting and pasting them into one file. I expect to use a lot of regular expressions to parse the files, and some hashes, arrays, and perhaps a bit more complex data structures like ArraysOfArrays, or HashesOfHashes, to store the information. Please slow down a bit here. Not that all these tools may not be called upon along the way, but this point is first to define the needed outcome, and then choose the tools needed at any stage along the way. The sample data you posted included a number of different types of information, each of which probably calls for special handling. Have you enumerated the specific types of information contained? You will probably need to do so. A well-named set of subroutines can make the task much easier. Something like-- my $box_score_ref = PlayByPlay-new('Lakers', 'Suns', 'Phoenix', '01/25/2004'); open PLAYS, 'play_by_play.txt' or die couldn't open raw report: $!; while (my $line = PLAYS) { if (my $shot = shot_taken($line)) { record_shot($shot); } elsif (my $penalty = penalty_on_play($line)) { reord_penalty($penalty); } eslif ... which will give you a great deal of lexibility in handling the differnt kinds of data and formats that these reports are throwing at you. Does that help? You tell us. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: returning hashes, and arrays
Stuart White wrote: I've tried this the only way I know how, which is to declare the subs with the number of arguments they are to take, and I believe the type of argument they are to output (like you might see in a C program), and then created my variables within the sub. Two things happened, when I couldn't get one of them to work and asked for help here, The problem here is that you are working with different syntax. Perl prototypes have a very specific meaning and purpose that is different than that used in C. I definitely enjoy--and prefer--using prototypes when working with C. In fact, I really don't have choice, but I find them useful. In Perl, you do the work elsewhere. A well-constructed first line or two in a subroutine can serve much the same purpose as a function signature: sub do_something { my $object = shift; my ($this_var, $that_var, $thuther_var) = @_; ... Since Perl is an untyped language, you are not going to get much more information from a header anyway, so the key is in choosing good, evocative names. It is very important, when working with any language, to take it on its own terms. Good practice for law, too. You could try looking at Perl subs as having a built-in prototype list sub (list @argv); This does shift the responsibility for validation into the implementation. You just have to work with that. Keeping your function definitions compact will help. If you can see all affected lines of the scope in one screen, it is much more straghtforward to evaluate what is going on throughout the function. That is another reason to avoid globals, and take references to any data you may have to modify as arguments to your subs. Sounds like this is frustrating for you, I know, but stick with it. Perl subs and scoping do have a logic of their own. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: returning hashes, and arrays
Stuart White wrote: You might want to depend on the documentation that comes with perl more than the book you are using. 'perlfunc' has a listing of almost all the the functions you'll see here. Perldoc.com has handy html documentation for the major versions of perl. 'Perlsub' does a better, deeper job than me with subroutines. Yeah, I had this problem before. Someone told me to go to STart-Program Files-ActiveSTate 5.8- Documentation This gave me what I find at the manpages, not perldoc. It was laid out well, but it was confusing. Same thing. The perldoc utility serves up man-pages in a system-independent manner using plain text. The ActiveState documentaion is the same POD converted to HTML. The only real difference that I can detect is the output format. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: returning hashes, and arrays
Stuart White wrote: I'm trying to decide if I want to take a break from this specific task and get into the examples of subroutines and references in my book. On the one hand, that should give me a much better grip on them, but on the other, that's time spent that I could be using to work on my own program. I could be taking a program that I know pretty well now, and tweak it to include references and subroutines, like I've been trying to do. I think it would be time well spent, presuming you have good, solid references. Getting a good grasp of the essential tools will save a great deal of time when you put your skills to work on practical projects. You do have to be ready to shift your paradigm just a bit, since perl is very much its own animal. Taken on itw own terms, though, it can be very effective and dependable. The main catch is that you have to choose that dependability, such as choosing to use strict. Joseph -- 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 data from table embedded in Word document
Andrew Gaffney wrote: The above code won't work because it splits on a comma. A lot of the fields contain a comma somewhere within the actual data. If it was easy as that, I would have had this done long ago ;) -- Andrew Gaffney Hi Andrew, Don't count on it not being that easy. Are you using the native capacities of the application to their best. I'm presuming here that a lawyer will have a full M$ Office suite, if they are u8sing the tools at all. You can paste tables from Word docs into Excel, and exoprt as CSV from there. Excel should have a much broader range of data export filters. It sound, though, like you will have a major job of normalization ahead. I would foresee a bit of hand work in the data design. One interim step you might take, for multivalued fields, is to concatenate them with some nuetral delimiter, such as a semi-colon. This way, as you normalize to break out any given field, you can use the Text::CSV module to get your fields, then split the fields of interest on the semicolons. If this material is already in an Office format, though, I would definitely recommend that you do as much as possible within Office. There is so much solid built-in functionality there that it wouldn't make sense to low-level something you can do with a macro. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: FW: Installing module.
Nilay Puri, Noida wrote: I am installing on sun os. perl versions is 5.8 While installing GD 1.19 module. I got error on running make test : make[1]: Leaving directory `/nilay/tars/GD-1.19/libgd' PERL_DL_NONLAZY=1 /usr/local/bin/perl -MExtUtils::Command::MM -e test_harne This is the second time I have seen test_harness broken. Could the identifier actuall be broken up in the make script or configuration file it came from? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: returning hashes, and arrays
Stuart White wrote: I'm having trouble returning a hash from a subroutine, and an array from a different subroutine. Beginning Perl said I could return a list, I can't get it to work. Must the hash and array really be a reference to the hash and array in order to return them? In brief, *Yes* You should get comfortable with this, if you have any desire to be a programmer. No matter what language you work in, power programming will largely depend on an understanding of references, and their close cousins, pointers. In not so brief, yes and no. It seems like the code should have returned a list of elements. Unfortunately, there is only one element, since you overwrite the whole array each time through the loop. I'm pretty sure the logic would have p[opulated the array other than this. It would still be quite wasteful, since this whole list would have to be recopied, where an anobynous hash would have already been packed for transit. I would really suggest that you overcome whatever resistance you have to working with references. If you approach them fresh, they are really rather straightforward. Put a little energy into getting over this hump in the learning curve, and you can reap benefits in all your programming efforts. Joseph -- 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 data from table embedded in Word document
Andrew Gaffney wrote: I'm writing a web-based client information system for a lawyer. [OT} Eek!! Be very, very careful about security, please. I trust your employer has taken duty of care isuues into account. [/OT] His current client list is in a 137 page Word document with an embedded table. I can get it into a somewhat usable format by copying the entire table, pasting into Excel, and saving as tab delimeted text, but this has its problems. Some of the cells in the table have newlines in them. Because of this, when it's exported from Excel, the 2nd line will appear in the correct field, but on a line by itself: Row 1, Firstname, Lastname,Address, City,State, Zip, Phone, AnotherPhone Don't export as space,-delimited. Use CSV, which is much more portable. Row 2, First middle, Last, addy,City,State, Zip, 555- So it looks like 3 records instead of 2. Does anyone have any ideas on how to pick apart the data to get it into the DB? -- Andrew Gaffney Hi Andrew, The problem here is more one of datqa design, specifically data normalization, than formatting. Neither documents nor spreadsheets are really good storage methods for large scale data. For long-term robustness, this data should probably be in a normalized database. Multi-valued fields generally indicate data that should be broken out into a table of its own: Assuming some unique ID for each client [*not* the name; names do not guarantee uniquesness], such a table could be very simple. client_id auto_number unique primary key client_phone character[20] primary_number boolean I'm a little rusty on my SQL today, so the types I list above are logical types. You will have to check your SQL reference to find the appropriate available types. These can easily be linked with simple SQL for presentation purposes. This structure also better supports working with the data of the fields broken out this way. I know this isn't a very Perl-ish response, but if you are going to rake on the task of working with this data anyway, you might as well do it right, and build something that will hold up over time. Then you can use querying tools or speadheets to prepare any needed presentation format. Now as far as the particular mehtod to use for picking the data apart, that depends. Is the phone number the only multivalued field? If so it should be fairly straightforward. It would help if we could actually see some of the data you have to work with. Might be a bit of work, since you will have to sustitute aliases--but realistic please, for any identifying information. Greetings! C:\Documents and Settings\rjnewtonperl -w my @rows; push @rows, $_ while STDIN; chomp @rows; my %phones; my $current_row_tag; my %data_rows; foreach $row (@rows) { last unless $row =~ /\S/; if ($row =~ /^\w/) { my ($row_tag, $given_name, $last_name, $streetaddress, $city, $state, $zip, $phone) = split /,\s*/, $row; $phones{$row_tag} = []; push @{$phones{$row_tag}}, $phone; my $customer_data = {}; $customer_data-{'given name'} = $given_name; $customer_data-{'last name'} = $last_name; $customer_data-{'street address'} = $streetaddress; $customer_data-{'City'} = $city; $customer_data-{'State'} = $state; $customer_data-{'Zip'} = $zip; $data_rows{$row_tag} = $customer_data; $current_row_tag = $row_tag; } else { $row =~ s/^\s*//; $row =~ s/\s*$//; push @{$phones{$current_row_tag}}, $row; } } foreach $client_id (sort keys %data_rows) { my $client = $data_rows{$client_id}; print $client-{'given name'} $client-{'last name'}\n; print $_\n foreach @{$phones{$client_id}}; } ^Z Row 1, Firstname, Lastname,Address, City,State, Zip, Phone, AnotherPhone Row 2, First middle, Last, addy,City,State, Zip, 555- ^Z Firstname Lastname Phone AnotherPhone First middle Last 555- HTH, Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Brain stuck on forming a hash
Chris Zimmerman wrote: Obviously I am a beginner, so bear with me: I have an array, @customers, that has a list of names. For each customer I need to read in a config file, $cust.morestuff.cfg which is formatted: Filename-mask Upload Name Hostname X-Type UserPass I need to generate something like this: $customer-$mask-@restofdata -$mask-@restofdata Skip this. Badly written code does not communicate anything. Dom't use code-ish symbols and all that garbage until you have the design logic worked out. Each customer will have multiple filemasks (basically the beginning couple of letters of the filename so I do not have to match exact files-some contain date names) with their appropriate processing information. I need to know the best way to get this together. Clear as mud? Expand on this. Do it in words and sentences, please. That is the best start to an effective program. The sentences can later be easily transformed into code with minor edits. What I can gather from the above is: You have a set of customers. Don't assume at this point that it will be an array, though. For each cutomer, you wish to store data grouped by some sort of filename mask. What are the files with these masks? What kind of information do you mean by @restofdata? This last is crucial, and should not be passed off cheaply. Thanks, Chris Zimmerman I would suggest that you rework your problem description. You do not, as yet, have any arrays--they are part of the program you will write. What do you have, in existence, to start with? What do you need to do with it? Do you want to create an index, maybe? The two questions above are the crucial ones going into any programming project. What do you have to work with, and what do you need as output of the process? You will get there much faster if you know where what your destination is. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Improving performance when working with large text files
James Edward Gray II wrote: On Mar 13, 2004, at 1:09 PM, R. Joseph Newton wrote: West, William M wrote: by slurping the WHOLE file into memory at once (do you have room to but a 45 megabyte file into memory?) the speed of the processing went up- Highly unlikely. There is no real speed advantage with Perl in slurping a file. Slurping certainly can be faster. I agree that it's not for everything, but it certainly has it's place. There's and excellent article on perl.com about this: http://www.perl.com/pub/a/2003/11/21/slurp.html James Thanks, James, I retested with a case similar to the first example cited in the article, and found that this was indeed the case. This certainly corresponds more closely to what intuition would indicate. About a year ago, though, when I was arguing the converse, the tests that I did showed very little speed advantage from slurping. The results may have been clouded by using the plain old CORE::time function and doing repeated opens of smallish files to get times sufficient to test with. The current tests used a moderately substantial text file--330 KB, and Time::HiRes, and showed an increase of more than 90% in processing time with line-by-line input. I will have to give some thought to the implications of this for programming practice. They probably will not be great. The actual time diference on this half-meg file was still only 4/100s of a second. By the time a file gets large enough that the time difference would get noticable, the file is probably also large enough to put a tax on memory resources for those who don't have 2 GB of RAM at their disposal. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: not getting the syntax
James Edward Gray II wrote: On Mar 13, 2004, at 12:36 AM, R. Joseph Newton wrote: Charlotte Hee wrote: $byname{ Owen }{ PHONE } = '999-'; Should be: $byname{ Owen }-{ PHONE } = '999-'; are you using strict? The code above should cause an error, not just an uninitialized variable warning. This isn't true. The arrow operator (-) is optional between [ ]s and { }s. The two lines above are identical as far as Perl is concerned and error free. James OK, I stand corrected on the issue of strict legality. I will still advise newbies to avoid the contracted version, though. The arrow operator there serves a very useful self-documenting purpose, IMHO, since it more closely reflects the logic of how the elements are accessed. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: second-level string interpolation
Michael C. Davis wrote: Hi, Apologies if I'm bringing up a repeated topic. I searched the list archive and the web and nothing specific has turned up so far. Is there a way to defer evaluation of the contents of a here-doc-defined value such that one can embed variables in the here-doc and not have them evaluated until they are used later? Something like this: It looks like you have gotten some good pointers to how you can accomplish this. I would suggest that you give some thought to whether it is a good idea to try this. What do you hope to accomplish by doing this? If you simply don't want to have the heredoc someplace where it interferes wh the flow of code, there is a much better, much less obfusciated way. code: - use strict; use warnings; my $header = 'end_of_header'; # File: $filename end_of_header my $filename = 'xyz'; print $header, \n; # output: want to see # File: xyz, but get # File: $filename I am not sure how the above is any more clear than it would be if you assigned a value to $filename first. I tried a few variations and nothing seems to work, as shown below. (This RFC http://dev.perl.org/perl6/rfc/229.html from Perl 6 implies that there is fact no way to do this.) Can anyone clarify. Thank you. How about this: Greetings! E:\d_drive\perlStuffperl -w use strict; use warnings; sub file_report_line { my $filename = shift; return END_STRING; # File: $filename END_STRING } my $filename = 'xyz'; print file_report_line($filename), \n ^Z # File: xyz Of course, the above code is rather senseless anyway, since it could be much more clearly written: return File: $filename; without all the baggage, but I am assuming that there is a bit more substance to your real heredoc. I still can't see a good reason for putting that low-level implementation detail at the top of the script, but this approach should work. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Improving performance when working with large text files
West, William M wrote: by slurping the WHOLE file into memory at once (do you have room to but a 45 megabyte file into memory?) the speed of the processing went up- Highly unlikely. There is no real speed advantage with Perl in slurping a file. The only good reason I can think of is if there is some reason that all data in the file must be cross-related in some way, and if the file data itself is already stored in some very condensed manner. ... pps- i just reread the question and realized that he was interested in reading the file in faster!! ok:: undef$/;#kills the 'line delimiter'- maybe local $/= undef; in #a subroutine is safer Nope. Reading it line by line is much more likely to speed up the process. Also, simplifying regexes will, even if it requires more regular expressions be run on each line. Regular expressions with fewer variables will run faster, because they will have fewer decisions to make. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Read from tape device
Jakob Kofoed wrote: Hi again, Hi, Sorry for the delayed answer. Tha's okay, but please don't top-post. Instead trim out anything to which you are noit directly replying, and follow comments with your specific responses, then add anything new in a block following. It helps to keep the flow of discussion cogent. Thank you for all your comments (Yes Joseph, I will try to enhance my basic abilities - sorry for the bad code:-) Actually, the issue is not so much code as meaning. As you translate a real-world problem into code, try not to let the meaning become less clear. Imagination helps considerably. If you have any way to visualize the matter your code is describing, try to do that. Then it should be much more clear what variable names would best describe the real-world matter. My thoughts on this project was to make a perl script which copy the content of a tape to disk, no matter if it is tar archives, binary files, EBCDIC and so on, much like the UNIX tcopy. Don't try to do it all with the same code. Instead of writing a script, write a program, with separate fucntions designed for each kind of file you may to encounter. You will save yourself a world of grief approaching the problem this way. But, I work on Linux and don't have the tcopy available. Oboy, I don't know about this. This seems like a prety demanding project. If this is production work, I would recommend that you Google for some product that has already ben proven, but... What is the format in which the tape files are stored? This is going to be critical. Since tape is a sequential medium, I assume that each file should be preceded by some form of header, rather than using a central directory as with a dsik I don't know, though. It is critical that, if you take on this project, you find out and use this information. Your best bet is to use file and block size information as you process. That is until(end_of_tape_reached()) { my $file_info = get_file_information(\*TAPE_STREAM); extract_file($file_info, \*TAPE_STREAM); } sub extract_file { my ($file_info, $tape_stream) = @_; my $file_type = $file_info-{'file type'}; my $storage_schema = $file_info-{storage schema'}; if ($file_type eq 'EBCIDIC') { extract_as_EBCIDIC($file_info, $storage_schema, $tape_stream); } elsif ($file_type eq 'binary') { extract_as_binary(($file_info, $storage_schema, $tape_stream); ... } } ... When you write multiple files to a tape it creates an physical end of file marker at the end of each file. When some applications write to tape they make an EOF between each file and then a double EOF at the end of the tape. I think you may be causing trouble for yourself trying to do character-based transfer. The difference in encodings should raise an alarm bell on that score. Why not look for the file size for each file to be transferred, and then use binary-mode IO? As I said, I really know nothing about the way files are stored on tape. The last tape drive I used was audio tape to load programs onto my Timex-Sinclair 1000. Yet I am fairly confident that the code above could serve as a driver for this process. Why? Because it is written at a high level, that allows it to direct the process while leaving implementation detail to the fuctions that it calls. That is the magic of structured programming. It allows you to focus on one level of abstraction at a time. HTH, Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: help with a regex and greediness
Stuart White wrote: $line = merlyn::118:10:Randal:/home/merlyn?/usr/bin/perl; @fields = s;oit(/:/,$line); #now @fields is (merlyn:, ,118,10,Randal,/home/merlyn,/usr/bin/perl) I don't think so: Greetings! E:\d_drive\perlStuffperl -w $line = merlyn::118:10:Randal:/home/merlyn?/usr/bin/perl; @fields = split(/:/,$line); print $_\n foreach @fields; ^Z merlyn 118 10 Randal /home/merlyn?/usr/bin/perl The only place a colon split splits is where you have a colon. I was having trouble using this example to figure out why my line wasn't splitting the way I wanted. So I included this line: $line = 'Spurs 94, Suns 82, Heat 99, Magic 74' then @result would look like this, right? @result[0] = 'Spurs 94' You should know better than this by now, with the help you've been getting. With that @ symbol, you are referring to a slice--an array of one element. *** When you are referring to a scalar, use the scalar symbol $ *** Yes, that was an error on my part. You're right, I know that it should have been $result[0] OK. It can be tricky, and it took me a few go-rounds to get that down. @result[1] = 'Suns 82' These first two make sense, pretty much. I think this is one place where $team1 and $team2 might be more sensible, though it is even better, if there is some order to which team is listed first in the pairing, to have you identifier reflect that order, say $home_team and $visitor [if these are accurate of course] I'll have to study the data to make sure that the home team and visiting teams are consistently in the same place. That's a good idea too. ...or you could even use $team_left and $team_right, since those terms would accurately describe the relative positions of the two substrings within each line. @result[2] = 'Heat 99' Going on to load more elements into the array does not make sense.. Does your data come in one continuous line, just a long string of team names separated by commas? Addressed above. OK. Sorry I missed the runup. My impression is that it came line by line. There would be no sense in doing the work of the split only to throw everything back in the same pile. There are a lot of different things you could do here, but the sensible ones would indicate that you should do something with the stats for each pairing before you go on to the next line. @result[3] = 'Magic 74' If I wanted to split on the numbers as well, why doesn't this work: @result = split (/\s*\d*,\s*\d*/, $line); The previous post already explained this, and you have seen the result of what you are trying. You can't do that because the information disappears if you use it in the split expression. I see. It seems that I didn't pick up on this entirely, though I do remember reading it. Splitting the lines into a pair of team-score combinations is one step. It deserves a line of its own. Extracting the name and score from each team-score clause is another step that deserves a line or three of its own. Ok, I didn't know this. I thought I could, and should do it all in one or two lines. I get confused about what data $_ has sometimes. This is a very good indicator that you should be using the default $_ less and named variables more. It all may look the same to the compiler, but since human error is the most likely cause of problems, it is more important to be as understandable as possible to the human reader. After I run the initial regex, I am usually extracting information from the backreferences. When those backreferences or $_ contain more info than I want, my solution is to tighten the original regex. You are suggesting that instead of that, I ought to just run a second regex on it, or a split on it in order to take the stress off of Perl and keep the program efficient, right? Is that what you are suggesting? Whenever possible, yes. Try to think through the process the regex engiine will take. The classic example is the line trim. You can do this $string =~ s /^\s*(.*?)\s*$/; and it will work, but the engine has to pack all the middle protion around. It works much better as: $string =~ s/^\s*/; $string =~ s/\s*$/; likewise a couple well-placed simple splits should handle you lines quite efficiently--and clearly my $scoreboard_left, $scoreboard_right = split /,\s*/, $scores_line; for ($scoreboard_left, $scoreboard_right) { my ($team_name, $score) = split /\s+/, $_; ...whatever you are doing with the score } I must confess that I am a bit at a loss as to what to do with the information at this point. I have forgotten what your goal is in terms of the form of output information you want. Presumably, you should have some structure ready to receive the information extracted here, so you can assign the value extracted to those structures. Though its Perl implementation is highly efficient, the regex process
Re: help with a regex and greediness
Stuart White wrote: the file format is not sloppy at all. I was just confused as to why I couldn't use split on the first space score comma and space, and then the next space score. -Perhaps I just answered my question right there, seeing that in the second iteration, there is no comma and then space. So are the team names all you want out of the lines? I guess I never fully absorbed that. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Reading text file in reverse order
Mame Mbodji wrote: This is a hwk, but I never asked for a complete answer 1. The term homework refers to something fluid, rather than discrete, and therefore does not take an article ['a' or 'the'] 2. Please do not abbreviate words, unless the abbreviation is a very standard one. I wasted 2-3 minutes just puzzling out what hwk meant: Hawk? some mispspelling or typographical error/ Who knows? There are enough accidental errors that get into e-mail traffic. There is no need to add those that arise simply from a lack of effort. When asking for guidance related to school studies, it is a good idea to explain what topics you are covering. The example problem you are working with can be handled in a number of ways. Which one may be most appropriate depends largely on what programming tools it is intended to help you learn about. Is the reverese function the focus of your studies? Have shoft or unshift come up in your class readings? Is the focus on handling string data? One thing I would suggest from seeing your code--you need to have more respect for the material. Int his code: while(my @line = REGFILE) { foreach my $lin(@line){ my @lines = $lin; print reverse(@lines); } } You use some variant or abbreviation for the word line in three different places. You do not use them sensibly. The plural of line is lines. This should probably be the name of the array, since it is the array that holds more than one line. The elements in each line are characters, not lines. Why do you call them @lines? That doesn't make sense. There are a number of simple ways to achieve the desired effect. Please rework your code, using variable names that indicate that you have put some serious thought into the problem, and repost. We can probably guide you towards some good solutions. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Reading text file in reverse order
John W. Krahn wrote: [EMAIL PROTECTED] wrote: I have a text file with 5 or more lines as in: My name is this and that I live in Denver Colorado I live in washington I live in Denver Virginia I am trying to read this file and print each line and each word in reverse order as in: ainigriv revned ni evil I (the output starts with the last last of the file and reverse each work as well). Here is what I have done, but does not work: print Enter a file name:\n; my $file = STDIN; open (REGFILE, $file) or die (Cannot open file: $file: $!); while(my @line = REGFILE) { foreach my $lin(@line){ my @lines = $lin; print reverse(@lines); } } use File::ReadBackwards; tie *FILE, 'File::ReadBackwards', $file or die Cannot open $file: $!; while ( FILE ) { chomp; print scalar reverse, \n; } __END__ Looks cool, and perfectly tailored to the task. How is it for handligg muti-charcter newlines? Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: can somebody tell me what this means
sam lehman wrote: so would: something ? dosomething : somethingelse ? dosomethingelse : killyourself be the same as Let's not go there--at least not yet. NOt that I object to suicide particularly, y'know dff'runt strokes fer diff'runt folks an' all, but nesting conditionals before you have used them properly is not good. Your speculation below is probably correct, but it is probably not a good use for your time. Better to learn how to put it to use than to seek for ways to abuse it. if (something){ indent properly, please. dosomething(); } elsif (somethingelse){ dosomethingelse(); }else{ killyourself(); } For more complicated situations like that presented here, it is much better to use the second form shown. I would also recommend the formatting changes shown, since they make it much more viually clear that this is a complex contidional as opposed to a series of discrete conditionals that just happen to occur in sequence. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: help with a regex and greediness
Stuart White wrote: Wow, yeah that helps a lot. Here's a question: If if had: $line = 'Spurs 94, Suns 82, Heat 99, Magic 74' and then did a split on comma and comma's surrounding spaces: @result = split (/\s*,\s*/, $line); result? How specific is result to the issue at hand? Would not $score then @result would look like this, right? @result[0] = 'Spurs 94' You should know better than this by now, with the help you've been getting. With that @ symbol, you are referring to a slice--an array of one element. *** When you are referring to a scalar, use the scalar symbol $ *** @result[1] = 'Suns 82' These first two make sense, pretty much. I think this is one place where $team1 and $team2 might be more sensible, though it is even better, if there is some order to which team is listed first in the pairing, to have you identifier reflect that order, say $home_team and $visitor [if these are accurate of course] @result[2] = 'Heat 99' Going on to load more elements into the array does not make sense.. Does your data come in one continuous line, just a long string of team names separated by commas? My impression is that it came line by line. There would be no sense in doing the work of the split only to throw everything back in the same pile. There are a lot of different things you could do here, but the sensible ones would indicate that you should do something with the stats for each pairing before you go on to the next line. @result[3] = 'Magic 74' If I wanted to split on the numbers as well, why doesn't this work: @result = split (/\s*\d*,\s*\d*/, $line); The previous post already explained this, and you have seen the result of what you are trying. You can't do that because the information disappears if you use it in the split expression. Splitting the lines into a pair of team-score combinations is one step. It deserves a line of its own. Extracting the name and score from each team-score clause is another step that deserves a line or three of its own. I just had a thought, it have to look more like: @result = split (/(\s*|\d*),\s*\d*/, $line); Unless there is a compelling reason why you must do all your regex work for a line in one pass, you are better off not doing so. Though its Perl implementation is highly efficient, the regex process is very costly, and the cost rises much more through complexity of expression than through multiple runs. Please review perldoc -f split for a better understanding. The split regex, is *what gets thrown away*. Do not put any data you may need in it. I think an earlier poster may have confused the issue with the zero-or-more spaces before the comma. Unless the file format is very sloppy, this should not be necessary. Assume decent data, split /,\*/, $line; should split a line into its comma delimited elements. Nor reason to try to get fancy here. Just split on the comma to get two elements. I'm confusing myself, but when I get home, I'll try out what you've shown me. That might be the way to do it. Keep it grounded--by choosing identifiers carefully to always communicate clearly what information they hold Keep it simple--most things are, if you let them be. Do one thing per line until you are using all of the basic constructs fluently. Pay close attention to the nature of each thing you are using a variable to describe, and make the containment class symbol [$, @, or %] that you use, reflects accurately whether you are referring to a container, or to an element held in the container. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: not getting the syntax
Charlotte Hee wrote: For a single record I can see how that works but let's say I have 4 or 5 employees and I have the employee information for each one (assumed). Now I want to build a record for each employee in a loop like this: @names = ('Jason','Aria','Samir','Owen'); foreach $na ( @names ) { So all the records differ only in name, and all other parameters stay the same? $record = { NAME = $na, EMPNO = $emp_no, TITLE = $title, AGE= $age, SALARY = $salary, PALS = [ $friend_list ], }; # store record $byname{ $record-{NAME} } = $record; } Now I want to add something later, after the record for the employee has been created. For example, I want to add the phone for Owen. When I try the following I get can't use undefined value Since you don't seem to be showing us the code you are actually using, we are somewhat at a disadvantage. ONe thing you should not, though. Since the nested hashes should be storedonly by reference, you should use the derefereing operator - to get at least the fianl element. $byname{ Owen }{ PHONE } = '999-'; Should be: $byname{ Owen }-{ PHONE } = '999-'; are you using strict? The code above should cause an error, not just an uninitialized variable warning. You really should put: use strict; use warnings; at the top of the script, and clean up the errors returned before you try to take on multidimensional structure problems. Houses built on sand cannot be expected to stand. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: FW: Win32::AdminMisc
Meneses, Alden wrote: Was able to download from www.roth.net Please don't top-post. Better to PPM for it. That tool is built into the ActiveState distribution. You might wish to add a couple sites to the repository: rep add Jenda http://Jenda.Krynicky.cz/perl rep add Roth http://www.roth.net/perl/packages/ rep add UWinnipeg http://theoryx5.uwinnipeg.ca/cgi-bin/ppmserver?urn:/PPMServer since the ActiveState sites are missing a lot of useful modules Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Some java some perl
[EMAIL PROTECTED] wrote: I'm doing one interface in java that will call some perl scripts. I need to catch the output and I don't know how to do it. If I execute the 'ls' command my java program finnish if I call the perl my program don't finnish. What am I missing? What are you expecting from your call to Perl? Note that shelling out has the same dangers with Java as with Perl. import java.io.DataInputStream; import java.io.IOException; public class Test { public static void main(String[] args) { try { Runtime r = Runtime.getRuntime(); String[] aStr = {-e, 'print(\Ola\n\) foreach (1..100);'}; Process p = r.exec(perl, aStr); You told the system to open the perl compiler here. You may also have Offered it 100 lines like this: Ola Ola Which Perl would have a very hard time interpreting as code. //Process p = r.exec(ls); DataInputStream strm = new DataInputStream(p.getInputStream()); String str; while ((str = strm.readLine()) != null){ System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } } } Thanks Marcos The code above is straight Java. Although it does inicdentally call the Perl interpreter, it is not presented with any further directions, and therefore does nothing. It is probably not the right place to discuss the Java Runtime::exec function. That would be more appropriate on a Java list [use Google to find one] For what it is worth, perl is generally called with a script name or code as the first parameter.. Please learn how to use each language well on its own before you try to develop cross-platform programs. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: backreferences
Stuart White wrote: Geez, I can't recall them covering (?: ) in my books...D'oh! The part about it grouping and capturing things makes sense, as it's the cousin of ( ). The part about being able to include the |'s doesn't. I found out, without knowing at the time, that the parentheses breakdown with |'s. I didn't know it at the time, but when I put the ORs in the parentheses and ran the program, I just got the command prompt, no output. Greetings! E:\d_drive\perlStuffperl -w my $string = 'Yada, yuda, heyho, whuzit'; my $regex = '(Y.{3}).*?(y.{3}).*?(boingo|eekers|heyho).*?(\w*)$'; if ($string =~ /$regex/i) { print $1\n$2\n$3\n$4\n; } ^Z Yada yuda heyho whuzit So the problem may lie elsewhere in the match. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Install Storable - ActiveState 5.6 Bld 623
Clinton James wrote: Hi ActiveState's documentation says Storable is in the Core. It's not in mine. Are you sure? Have you tried: Your_prompt perldoc Storable at the command line? If the documentation is there, the functionality probably is also. You can also make at least a quick and dirty check for functionality itself by: Your_prompt perl -MStorable If Perl can not load Storable.pm, it will squack when the use-module switch for Storable is specified on the command line. There is no binary available. I downloaded v2.04, v2.08, v2.10 from CPAN and ran each Better to use CPAN--even if it's broken, which mine is. Even crippling along it seems to get the job done on modules for which no ppm is available. Try: perl -MCPAN -e shell cpan install Storable You mentioned the version of the module you downloaded, but have not told us what Perl version you are running. What leads you to believe that Storable is not available in your installation? Have you done much of the low-level installation approach you describe above? It is usually not good for your Perl installation, unless you have a very comprehensive understanding of its structure. Use ppm first. If ppm fails, try using CPAN. Only if neither of the built-in installation facilities is successful should you resort to hand installation. I'd suggest first making sure that the module is not loaded. If not, please post again and let us know what Perl version you are running. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Read from tape device
[EMAIL PROTECTED] wrote: Hi All, I am trying to read some data from af unix tape device. The have several files with end of file markers. Can I read from tape devices at all? I tried open on the device and this one reads all files on the tape into the first file and then hangs. Is it my code (I know the first loop is not very good:-) or does perl not recognise or honer the EOF marks? Thanks, Jakob my $cnt = 0; while (1 == 1) { open IN, , /dev/nst0 || die cant open ...\n; while (@out = IN) { Why are you using an array?. That puts the read operator in list context, so that it reads all lines of the file into the @out array on the first round through the loop. $cnt++; Please use vowels. They are neither poisonous nor explosive. open OUT, , $cnt.bin || die cant open out\n; print OUT @out\n; close OUT; } } close IN; The code above probably does exactly what you are telling it to do. On the first round, it sucks all lines offered in text mode by the strream from the tape drive. Then it reaches EOF. At this point there is nothing left to read in the file, so the whole array, containing the first text file on the tape, is output to the file. It is good that you have an ambitious project in mind for Perl programming. I suspect that you will need to get much more familiar with the basics of Perl programming, as well as general file-storage principles, before you can do justice to the job. Have you had success in reading and processing individual files in a variety of situations? This would be a good place to start. Joseph -- 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 hash list for CGI Form
Scott Taylor wrote: Hello all, When I populate this hash (%SrcIDs) from SELECT id, desc, from myTable order by desc it What does it refer to here? If you mean the SQL engine, which does care about the content of order clauses, you are mistaken. Your data set is returned in the proper order. Since you have already done oredring, which you wish to preserve, you might be better off, pushing each record into an array. If it above refers to the Perl hash, that is true. Perl hashes make no promiswes about their internal ordering. You order the *output of* data stored in a ahs by applying the appropriate sort to its keys. doesn't order by the description field desc. (printing each row in the while loop show that the SQL is sorted) The test does not answer the question you think it does. Try printing each line as you are getting it from the fetchrow function. while( my($id, $desc) = $sth-fetchrow ) { $SrcIDs{$id} = $desc; You say above that you are ordering by the desc field. If so, you should probably be using desc as the keys. If more than one id has the same desc, then you have a small problem. That can be remedied by using an anonymous arrays of ids as the vlues for each keys } $sth-finish; while( my($id, $description) = $sth-fetchrow ) { $source_ids{$description} = [] unless $source_ids{$description}; push @{$source_ids{$description}}, $id; } my @Sources = keys(%SrcIDs); # Begin HTML print header('text/html'); print start_html('Select Source Mill Info Page'), h3('Select Source Mill'), startform('GET','srcmill.cgi','','gosrcmill','_blank'), Source Mill: nbsp, popup_menu('millid', [EMAIL PROTECTED], '', \%SrcIDs),p, ... So, you see I want to link @Sources with the keys of %SrcIDs, but what I want is to sort the hash alphabetically by the values of %SrcIDs. Please, how can I do that? To start with, describe your desired results in terms of outcomes rather than process. Instead of putting the information into a data strucure that you then have to twist for desired results, just describe what you want. I am going to assume that you meant: I would like to fill a list with the IDs, sorted by the description field. Taking the structure I showed above, this is easy: my @flat_id_list; foreach $description (sort keys %source_ids) { push @flat_id_list; (sort {$a = $b} @{$source_ids{$description}}); } This should provide the ordering you sought. The IDs conatained in @flat_id_list will now be ordered by the description field. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: HERE DOCUMENTS and teachable moments
WC -Sx- Jones wrote: Serguei Krivov wrote: Bill, Would it not be better to post (copy) this message and the following postings to perl.tips oriented for beginners (like me) http://www.nntp.perl.org/group/perl.tips Later it is going to be much easier to search perl.tips with 8 messages posted up to date then go through 61314 messages in perl.beginners. Yes. But wouldn't it be only 61_314Base36 messages? :) ... I am both pleased and annoyed that I have gotten very little flames over my How To posting -- not that I want to annoy people, I don't; I am simply trying to condense certain questions and thoughts that I myself had when I was starting out so that others may say 'Ohh ... I see.' Well, that is cool. The only problem is that it is not always likely to reach the people who need it. Generally those who have not leaned to use the perldoc utility may also not carefully peruse the threads for related topics. So your thread, with eactly the information someone needs in a given situation, might languish unread while the student thrashes. Better just to respond to the situations as they arise. Sometimes this will mean pointing a person back to a recent thread that they *really should have* read themselves before posting. Sometimes a thread may also lead to other questions about the approach a person is taking to learning Perl, or to structuring problems. Message threads can take some interesting courses, and it is not only more spontaneous, but also more information-efficient, to make the knowledge meaningful in its context, to find the teachable moment. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: comparing a string to elements of an array
Stuart White wrote: In the end, I want @SAN to have all the unique names within the file. Any ideas? You just described a Hash. Use %hash and then either uppercase or lowercase the the incoming key. YOu could then add a count to the Hash so you know you are looking at all things or not. The keys for a hash can only appear once(ie, San and SAn are two different keys) that is why you should uppper or lower the keys. Wags ;) If I had a hash, I'd have to have a key and a value though. If you are counting the strings as they are found, there is a relevant value--the count. If not, there is still a value, found [true = 1, false = undef or 0] associated with it. This is the standard Perl way toguarantee uniqueness. my $found = {}; my %count = (); foreach (@big_bag) { $found-{$_} = 1 unless $found-{$_}; $count{$_}++; } I'm just looking for one or the other. I suppose I could have key value pairs in the %SAN hash like so: Parker:san Bowen:san etc Then I'd probably stick all of the keys into an array. However, using a hash I wouldn't have to use a foreach loop or an unless, would I? Huh? Use a foreach loop to accomplish what purpose? You can definitely access any given element in a hash without iterating through the structure for it. The internal implementation of a hash access is an O(1) process. That is, there is no particular penalty for size of container. This is another good reason to use hashes in such cases. The even better reason in this context is that hashes have uniqueness of keys built into their design, while arrays do not. That would make the Parker:san format and then dumping the keys into an array worth it. You lost me here. Instead of speaking in terms of program structures, can you describe your problem in terms of what information you wish to produce out of this? What form does the data take coming in? What is the form of the desired output information? I see you getting yourself boxed in a lot by premature selection of data structures. Much better to describe the problem clearly in plain language first. The appropriate data structures can be settled on after you develop your overall plan of action. Okay, I just read the other branch of this thread, and it look like you want to extract a simple list of the players names, with no duplicates. Wow, this has been some merry-go-round for an essentially simple problem. Without the premature focus on program structures, it would have been quickly resolved. A clear and simple specification will take you much farther than even the most clever coding trick. Focus on the logic. The code will follow. Joseph -- 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 big is my data structure
WC -Sx- Jones wrote: Michael C. Davis wrote: Hi, is there a good way to tell how much memory a given data structure is consuming? I realize that there are issues in using this number to determine runtime memory requirements (like the fact that, in some circumstances, a running Perl process does not give back allocated memory to the operating system until the process exits) but ... are there guidelines like 100 bytes per REF, for example? Or is there a routine to which I can pass my data structure and have it tell me the size? Thanks! There is likely a shoreter trick, but to give you an idea path to follow - my @array; my $size = length @array; print $size\n\n; @array = qw/one two three four/; $size = length @array; print $size\n\n; $size = 0; foreach (@array) { $size += length; } print $size\n\n; __END__ Sorry, but that's not really going to say much about memory itself. Perl is not C, and this is one place where the difference really shows up. To dtermine memory requirements, you would have also to determine the overhead-per-variable, and add that into the formula. In Perl, this can be very significant. Joseph -- 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 big is my data structure
Michael C. Davis wrote: Hi, is there a good way to tell how much memory a given data structure is consuming? I realize that there are issues in using this number to determine runtime memory requirements (like the fact that, in some circumstances, a running Perl process does not give back allocated memory to the operating system until the process exits) but ... are there guidelines like 100 bytes per REF, for example? Or is there a routine to which I can pass my data structure and have it tell me the size? Thanks! My suggestion would be to fill containers with variables of whatever kind you are interested in, and use system monitoring tools to see how much memoryu your process consumes. When I did some exrcises testing for memory usage, for instance, the readings indicates that empty anonymous hashes could take about 60-70 bytes apiece. This ballpark figure was good enough for me. It may be that, by perusing perldoc perlguts you can garner sufficiient information to precisely calculate what the memory cost of any scalar or container is. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Browser-specific perl error (taint mode)
Erik Rieselbach wrote: Hi, Can anyone explain to me why I would get a perl error in one web browser but not in any others? This depends on on alot of factors, few of which you are sharing.Generally, perl errors should not come through to the browser. IIS does pass error messages through by default. That is a server-side question, though. *The browser and Perl code have nothing directly, to do with each other* Tthe browser may be returning information to the server in a way that causes these errors All I¹m doing is taking an email address from a form, feeding it to a validation sub that untaints it, then using it with the f option to sendmail. It works fine in Mozilla browsers on both Mac and PC, as well as in Safari on the Mac, but Internet Explorer on either platform gives ³Insecure dependency in piped open while running with -T switch² at the line where I open a pipe to sendmail. It is possible that your server can not negotiate a secure protocol with IE. You are using user-provided data as a parameter to a shell command, also. Unless Perl recognizes your validate_email_address as a sufficient filter, it may assume that this data could contain malicious code. from perldoc perlsec: You may not use data derived from outside your program to affect something else outside your program--at least, not by accident. All command line arguments, environment variables, locale information (see perllocale), results of certain system calls (readdir(), readlink(), the variable of shmread(), the messages returned by msgrcv(), the password, gcos and shell fields returned by the getpwxxx() calls), and all file input are marked as tainted. Tainted data may not be used directly or indirectly in any command that invokes a sub-shell, nor in any command that modifies files, directories, or processes, with the following exceptions: ... my $user_email = validate_email_address( param( Email ) ); ... open MAIL, | /usr/lib/sendmail -t -i -f '$user_email' or die Could not open sendmail: $!; Use Perl. There are a number of modules which do not require external programs to send mail. The validate_email_address sub comes straight from ³CGI Programming with Perl² chapter 9. It¹s too long to include here but its final line is return $addr_to_check =~ /^$address$/ox ? $addr_to_check : ; Any ideas on why this might be happening would be greatly appreciated. I'm more puzzled on why you are not getting this error when the client browser is Mozilla. Perl's taint function does not evaluate your validation function to see whether it is sufficient to prevent [EMAIL PROTECTED] rm * From being passed through to the command line. It just knows that you should be alerted to the potential. Joseph -- 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 array as First argument
zsdc wrote: Mallik wrote: Dear Friends, I need to pass 3 parameters to a subroutine, in which the first parameter is an array and the last two parameters are strings. @abc = qw(1 2 3); $x = 4; $y = 5; testsub(@abc, $x, $y); Hello Mallik, I've just read this thread and I'd like to add one more way to solve your problem in addition to solutions already posted by Joseph, William, Jim and David. This is quite a common and simple problem for which reading the whole perldoc perlsub might be somewhat too confusing, but asking about it on mailing lists usually starts discussions which often become arguments on whose favorite style is better, so I'll do my best to describe every possible way as objectively as I can, and then I'll say which style I would personally use in which circumstances. In general, you can pass an array to a subroutine in two ways: as a flattened list of scalars (its elements), or by reference. (Every subroutine call in Perl passes the arguments as a single flat list of scalars, but one of those scalars might just happen to be a reference to your array.) Thans for an excellent summary. I must admit I have been a bit strident in advocating a pass the references as explicit scalars approach. I really do think that the use of references is a concept that beginners should be encouraged to wrap their heads around from the start. It really is a very simple concept, complicated largely by a mystique of difficulty that has somehow accrued around it. I usually operate on the assumption that arrays are, or could grow to be, of production scale. With large scale, even in a by-value context, references offer a great efficiency. They also have implicit dangers. The writer of any function should be very careful to indicate whether the function operates on the referents of the arguments. The user of any function should be aware of whether it operates on, or simply uses the values from, the original. This sort of attention is necessary in any case, though. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: listing prime numbers in a range (Beginning Perl exercise)
Stuart White wrote: This was my first chance at testing this, and it did work. How, I'm not sure though. Specifically: What do you call the PRIMES: and __END___ syntax? The two are not directly related. The way PRIMES is used here makes it a label. This allows rapid, uncomplicated iteration through the outer list if $possible_prime is evenly divisible by, and thus has modulus zero in relation to, $test; The __END__ syntax, on the other hand, tells the Perl interpreter tthat the end of profram code has been reached for the file. It can be useful if the code section is followed by either documentation or data. With documentation, it prevents the interpreter from taking the text as code. If you have a reference to DATA, Perl will also look in the section following __END__ or __DATA__ for the data to be processed. Greetings! E:\d_drive\perlStuffperl -w while (DATA) { print; } __END__ Hello Hello Goodbye Goodbye ^Z I just checked, and this is special magic with the __END__ and __DATA__ tags. For instance: Greetings! E:\d_drive\perlStuffperl -w while (DATA) { print; } __JABBERWOCK__ Hello Does not work, as we can see. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Checking filenames? [:: ?Kinda Solved? ::]
WC -Sx- Jones wrote: Hmmm, I get 3 Indians in only the first variable anyways =/ Doesn't surprise me. The x is a concatentation multiplierfor strings. Why not just say what you want: $_ = 'Litttle' for my ($onelittle, $twolittle, $threelittle, ) ; print 1 $onelittle 2 $twolittle 3 $threelittle Euro-American Doughblobs\n\n; One thing notable about all of this is that no work is saved, or very little. Hmmm... my $number_names = [qw /Zero One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Noneteen / ]; # Yeah, we only need 1..3, but I only want to write that once per language. print $number_names-[$_] little for (1..3); print Euro-American Doughblobs\n\n; Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Reading File grep according item 5 and sorting
Bjorn Van Blanckenberg wrote: On 3-mrt-04, at 09:56, R. Joseph Newton wrote: I understand how the code works It reads the file end split every line according to the tabs and then sorts everything. For returning the info it looks at colomn 5 (1-based indexing) and if colomn 5 of the next line is the different print an extra newline. So it basically does what I want if colomn 5 is exact the same not if it start with string from colomn 5. So It is basically what I need but without reordering (sorting) and looking at every line that starts with colomn 5 and then sorts that blok of tekst. I hope I explaned it well enough. Thanks Well, that is good, but it leaves you having to do a lot of work over again, mostly because you handled things in a limp early on. That bit of code early on: my @sorted = map { $_-[0] } sort { $a-[5] cmp $b-[5] } map { [ $_ , (split /\s+/) ] } @fields; does a sort, then re-concatenates the lines as sorted. Then they have to be picked apart again in order to look for places to insert a newline. What you want to do will require design, not imitation. First, think about the requirements per line: While the fifth token in the line is the same [which none are, since they all have different decimals slopped onto the end], you wish to collect them in a group. Then you want to print out the items in the group line by line. If you want groups of lines, why are you throwing them together into a garbage bag of an array? my %fifth_item_groups; while (my $line = INFILE) { chomp $line; next unless $line; my @tokens = split /\s+/, $line; my $fifth_item = $tokens[4]; $fifth_item =~ s/\d+$//; $fifth_item_groups{$fifth_item} = [] unless $fifth_item_groups{$fifth_item}; push @{$fifth_item_groups{$fifth_item}}, [EMAIL PROTECTED]; } foreach my $grouping_key (sort {$a cmp $b} keys %fifth_item_groups) { print join(\t, @{$_}), \n foreach @{$fifth_item_groups{$grouping_key}}; print \n; } The code above should perform the task specified--with no subsort. That work is for you to do. Hint: I chse my data structures pretty carefully, so that you should not have much trouble accessing any element by which you might wish to do a subsort. When you have made use of this and added the subsort, please post again and show us what you come up with. Joseph -- 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 array as First argument
William Gunther wrote: If a beginner can understand the concept of prototyping and referencing, I think they can gather an array reference is being passed. Actually no. I have not seen this in the last year of reading this list. The vast majority of newbie traffic that i have seen among the 22K+ posts inmy archives provides strong indicatins of resistance to understanding references. Syntactic tricks that allow beginners to offer aguments without explicit referencing only fuzz up the matter. At a later stage in development, perhaps, the prototyped form with the reference to type indicator may be helpful, because it provides added information about the function--when looking at the prototype. Joseph -- 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 in array accessing
zsdc wrote: R. Joseph Newton wrote: N, Guruguhan (GEAE, Foreign National, EACOE) wrote: @temp = INPUT ; Here is your immediate problem. The line above puts the first line of the file into the first element of @temp. If you must dump all your data into an array, then you will have to put the input operation into list context by enclosing it in parentheses: @temp = (INPUT); The assignment to array already provides the list context, so: @temp = INPUT; is equivalent to @temp = (INPUT); reading whole INPUT, and not: @temp = scalar INPUT; which would read one line of INPUT and store it in the first element of one-element @temp array. -- ZSDC Thanks for the catch. I should have tested. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response