d5e5 109 Master Poster

I don't have Windows 7 but the code you posted has a syntax error.

#Root.geometry("%dx%d")%(RWidth,RHeight) #_tkinter.TclError: bad geometry specifier "%dx%d"
#Replace with the following line
Root.geometry("%dx%d+0+0" % (RWidth, RHeight))
d5e5 109 Master Poster

Please start a new thread to ask your question instead of replying to a three-year old thread.

When you post your question, please include your script, invoice.pl, wrapped in [CODE]Your invoice.pl script goes here[/CODE] tags. We can't help you with this kind of error unless we know what you are trying to do and how you are trying to do it.

d5e5 109 Master Poster

To fix it, add a newline character immediately after FOOTER. Like this:

#!/usr/bin/perl
use strict;
use warnings;
print <<FOOTER;
</body> <! --end tag for main page section -->
</html>	<!-- end tag for entire HTML page -->
FOOTER
#Had to add newline after FOOTER
#to avoid "Can't find the string terminator..." error

Now output is

</body> <! --end tag for main page section -->
</html>	<!-- end tag for entire HTML page -->

See http://www.perlmonks.org/?node_id=686004 for some explanations.

d5e5 109 Master Poster

And OP must add the recursion?
To only check if things are palindrome is by the way enough to:

def ispalindrome(x): return x == x[::-1]

(The recursive version can be written with same amount of lines)

I like that. It's much shorter than what I was thinking of. However the OP says that palindromes can be sentences as well as single words, so the function perhaps should also remove all punctuation and spaces from the input string before testing it the first time. That way it could handle palindromic sentences such as, "Red Roses run no risk, sir, on nurses order."

d5e5 109 Master Poster

The following statement fails to specify the file open mode. The default mode of read only is assumed. open(OUT,"LuContig091010RNAcomp.fa")or die $!;#No redirection character so file is opened in read mode I prefer the 3-argument version of the open, like this: open( OUT, ">", "LuContig091010RNAcomp.fa" ) || die "Can't create output file $!"; See http://perldoc.perl.org/perlopentut.html#Simple-Opens

d5e5 109 Master Poster

@snippsat

Thank-you, but can you please will this work if i'm reading the file from a list? My project requires me to create a def function that can convert the list of numbers into a number before I can get the average. Btw am I able to put anything in the brackets at the last line you've indicated? Sorry for being so noob :(

"...reading the file from a list?" You mean reading a file into a list? If so, please post the contents of the file between [CODE=text] [/code] tags so we can see how many numbers per line, what character occurs between the numbers (space, tab, comma, etc.) and what other characters are in the file besides numbers.

By "...convert the list of numbers into a number before I can get the average" do you mean add the list of numbers to get a total? That's what sum(numList) does in snippsat's function.

d5e5 109 Master Poster

Sorry for the confusion. The error message I posted was caused by a print statement I inserted to print the value of $count before incrementing it. The following modified version of your script seems to work for me now. I'm not sure why.

#!/usr/bin/perl
#countvisits.cgi
use strict;
use warnings;

use CGI qw(:standard -debug);
use CGI::Carp qw(fatalsToBrowser);

#declare variables
my ($count, $C_record);

#Create a new CGI object
my $cgi = new CGI;

#Read the cookie
#assign input to variable
$count=$cgi->cookie('count');

$count++;
  
#create cookie
$C_record = cookie(-name => "count",
                 -value => $count,
                 -expires => "6M");
 
 
#send cookie to browser
print header(-cookie => $C_record);

#create Web page
print "<HTML>\n";
print "<HEAD><TITLE>Jubilee Book Club</TITLE></HEAD>\n";
print "<BODY>\n";
print "<H1 ALIGN=center>Hello!<BR>\n";
print "You have been here $count times.</H1>\n";
print "</BODY></HTML>\n";
d5e5 109 Master Poster

The script doesn't appear to read the cookie. In your error log (or whatever file STDERR writes to) you may find something like "Use of uninitialized value $count in concatenation (.) or string at..."

d5e5 109 Master Poster

I have Python 2.6 and it worked fine for me without my uncommenting #n = fin.readline() or anything else. I made no changes except the file path and it showed me a word count for the my file (not the constitution but some other file in my folder).

When it doesn't work for you, does the wordTotal variable equal zero, or in what way does it not work?

d5e5 109 Master Poster

looks great! thanks d5e5!

You're welcome. After posting that I realised I had assumed the input data had already been sorted by group and location, as your latest input data appeared to be. If future input data does not come in that sequence you will need to add the following line after @in has been built, and before processing it. @in = sort my_sort @in;

d5e5 109 Master Poster

Please try this approach.

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

my (@in, @out);
while(<DATA>){
    chomp;
    push @in, [split(/\t/)];#Build an array of arrays
}

my $prev_aref;
foreach my $aref (@in){#foreach array reference
    if (!defined($prev_aref)
        or $$aref[1] ne $$prev_aref[1]
        or abs($$aref[2] - $$prev_aref[2]) >= 250){#At least 250 away from prev loc
        push @out, $aref;
        $prev_aref = $aref;
    }
}

@out = sort my_sort @out;

foreach my $aref (@out){
    print join "\t", @$aref, "\n";
}

sub my_sort{
    my $r = $$a[1] cmp $$b[1]; #Compare group
    if ($r == 0) { #If group in same group
        $r = $$a[2] <=> $$b[2]; #Compare location
    }
    return $r;
}
__DATA__
12	scaffold534_10_	147	-103	397	D	mdv1-miR-M3*_MI	-1	1.77e+02
12	scaffold534_10_	1391	1141	1641	D	mdv1-miR-M3*_MI	-2	2.92e+03
19	scaffold534_10_	1525	1275	1775	D	cin-miR-4218-5p	-2	4.62e-01
16	scaffold534_10_	5765	5515	6015	D	mmu-miR-546_MIM	-2	2.07e+01
21	scaffold534_10_	6625	6375	6875	D	ath-miR414_MIMA	-2	3.54e-02
12	scaffold534_13_	1969	1719	2219	D	mdv1-miR-M3*_MI	-2	2.92e+03
18	scaffold534_15_	208	-42	458	D	cin-miR-4194-3p	-2	1.65e+00
12	scaffold534_16_	8087	7837	8337	D	mdv1-miR-M3*_MI	-2	2.92e+03
19	scaffold534_16_	16182	15932	16432	D	gma-miR1533_MIM	-2	4.62e-01
19	scaffold534_16_	16185	15935	16435	D	gma-miR1533_MIM	-2	4.62e-01
19	scaffold534_16_	16188	15938	16438	D	gma-miR1533_MIM	-2	4.62e-01
19	scaffold534_16_	16191	15941	16441	D	gma-miR1533_MIM	-2	4.62e-01
19	scaffold534_16_	16194	15944	16444	D	gma-miR1533_MIM	-2	4.62e-01
12	scaffold534_16_	17672	17422	17922	D	mdv1-miR-M3*_MI	-2	2.92e+03

This gives the following output.

12	scaffold534_10_	147	-103	397	D	mdv1-miR-M3*_MI	-1	1.77e+02	
12	scaffold534_10_	1391	1141	1641 …
d5e5 109 Master Poster
for word in words:
        if word in d:
            continue
        else:
            #d[words] = words This is wrong. You want word, not words
            d[word] = word #This should work
d5e5 109 Master Poster

Please wrap your program in [code] Your program goes here [/code] tags. Otherwise we can't see how the lines in your program are indented and have to guess.

d5e5 109 Master Poster

David,

My link to that perl module does everything stat-wise, including standard deviation. I guess it begs the question: WHY is he writing the program? It's it for a class assignment? To show someone else he can program in perl? I don't know why, but IMO I always try to go to CPAN to set if someone else has written it, and if so, it's probably better than I can write :-)

Mike

Mike,

I agree that to do a commonly-required task in perl it makes a lot of sense to look for a module on CPAN that does it instead of struggling to re-invent the wheel. If I needed to calculate standard deviation I would definitely take your advice and use Statistics::Descriptive.

My reply above assumes that the problem is a school assignment that doesn't allow using module methods to do the required calculations (although I still think the teacher should insist on use strict; and use warnings; as good progr.amming practice.) I don't intend to do the assignment myself, of course. My example tries to show the right way to pass arguments to a subroutine and return a value nicely -- instead of a subroutine that creates a bunch of global variables. Subroutines assigning results to global variables can get the job done but tend too make scripts difficult to understand and debug.

I agree that to accomplish a task at work or for some goal other than practising the writing of subroutines, the first …

d5e5 109 Master Poster

How do you write a perl script to determine the number of measurements, average, variance, standard deviation?
This is the script that I have so far and it is not working.

my @data = (6, 9, 7, 23, 30, 18);
my @data2 = (10, 5, 8, 11);
my @data3 = (12, 15, 13, 19, 5, 8, 10);
Data_info('Info',@data);
Data_info('Info',@data2);
Data_info('Info',@data3);

sub Data_info{
my($Data_info,@activity) = @_;
my ($num)=@Data_info +0;
my ($sum)=0;
my ($sqsum)=0;
foreach $x (@Data_info) {
$sum += $x;

$sqsum += $x * $x;

}

my ($avg)=$sum/$num;
my ($var)=$sqsum/$num-$avg*$avg;
my ($stand_dev)=sqrt ($var);

print "$Data_info:\n",
"Number of measurements = $num\n",
"Average = $avg\n",
"Variance = $var\n",
"Standard Deviation = $stand_dev\n\n";

  • Please post your script between [code]

    [/code] tags.

  • Two statements to include in your script are use strict; and use warnings;
  • Why are you passing a literal 'Info' to your subroutine with your array?
  • Remember that when you pass more than one argument to a subroutine, all the arguments are combined into one array. This is one reason your script doesn't work.
  • It's better to return a value from a subroutine and assign the value to a variable in the calling statement.

You can google perl calculate average and copy a pretty good subroutine from wiki.answers.com and call it like this:

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

my @data = (6, 9, 7, 23, 30, 18);

my $avg …
d5e5 109 Master Poster

I don't know the source of the problem with your script and can't say if the problem resides in $_ because I don't see where any value is assigned to $_ or $delim. What I can do is try to fix my script so it won't reject blank input.

What I suspect happened when you tested my script: your file of regex patterns may have included a blank record (just an extra carriage-return/line-feed character would do it) which resulted in an element containing a string made up of whitespace characters or nothing at all being included in the array I use to build the $pattern. I can fix that by removing any zero-length elements from the array before building the pattern. Please try the following:

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

#You can open a file and read from it.
#Here I read from my <DATA> handle for convenience.
#The point is, you want your regex patterns stored
#in an array.
my @arr = <DATA>;
foreach (@arr){
    s/^\s+//;#Remove leading whitespace
    s/\s+$//;#Remove trailing whitespace
    $_ = quotemeta($_); #Escape characters such as $, ., etc,
}

@arr = grep(length($_) > 0, @arr); #Weed out all zero-length elements

my $pattern = '(' . join('|', @arr) . ')';

#Now let's say you read two input records from <STDIN> (not shown here)
#and assign them to $input1 and $input2
my $input1 = "GET / HTTP/1.0";
my $input2 = "Windows NT 5.2; en-US; rv:1.9.1.6; Major 3.0)";
my $input3 = "\t   \n"; #Input can be all …
d5e5 109 Master Poster

Since you want to use text from a file to construct a regex pattern, you need to remember to escape the characters in this text that would otherwise have special significance to regex. You can use the quotemeta() function to do this.

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

#You can open a file and read from it.
#Here I read from my <DATA> handle for convenience.
#The point is, you want your regex patterns stored
#in an array.
my @arr = <DATA>;
foreach (@arr){
    s/^\s+//;#Remove leading whitespace
    s/\s+$//;#Remove trailing whitespace
    $_ = quotemeta($_); #Escape characters such as $, ., etc,
}
my $pattern = '(' . join('|', @arr) . ')';

#Now let's say you read two input records from <STDIN> (not shown here)
#and assign them to $input1 and $input2
my $input1 = "GET / HTTP/1.0";
my $input2 = "Windows NT 5.2; en-US; rv:1.9.1.6; Major 3.0)";

#Testing $input1
if ($input1 =~ m/$pattern/){
    print "Reject$input1\n"; #Matches
}else{
    print "$input1\n"; #No match
}

#Testing $input2
if ($input2 =~ m/$pattern/){
    print "Reject$input2\n"; #Matches
}else{
    print "$input2\n"; #No match
}

__DATA__
Major
Minor
$Low
High
High /3.21 www.heal.com
$Major
d5e5 109 Master Poster

Well sorry to divert a little from here.

simple Print will not remove quotes in a hash my good friend.
I know you know that yourself. ;)
...

I do know that print; will not remove quotes from data stored in a hash, but I don't see any hash in your example. Maybe I'm missing the point but in your example I don't see how print(s/\",'*//,$_); does anything more that print; .

I think s/\",'*// says "remove all strings consisting of a double-quote followed by a comma followed by zero or more single-quotes." That won't do anything because the data probably won't contain strings of those characters in precisely that sequence. Perhaps you meant to define a character class and forgot the square brackets?

An example of removing quotes from data read from a tab-delimited file before storing that data in a hash would be something like

#!/usr/bin/perl
use strict;
use warnings;
#file2hash.pl

my %h; #Store each unique word from file as key in hash
while(<DATA>){
    chomp;
    my @words = split(/\t/, $_); #Store words in array.
    foreach(@words){
        s/"//g; #Remove double quotes before storing word in hash.
        undef($h{$_}); #Store word as key in hash. Value is not defined.
    }
}

foreach(keys %h){
    print "$_\n";
}

__DATA__
"here"	"is"	"a"
"tab-delimited"	"file"
"with"	"quotes"	"around"
"the"	"text"

Comparing these keys to another list in another hash could be done pretty much as in mitchems example.

d5e5 109 Master Poster

You want simple one.
Check this out.

my @S=("hello","ben","foo",,"","bar","rose","world","foo",'loo');

foreach (@S)
{
	print(s/\",'*//,$_);
	print "\t";
	}




## OUT PUT

hello    ben     foo    bar     rose    world    loo

In the above example there is nothing to remove. You will find that replacing print(s/\",'*//,$_); with a simple print; will give the same output.

d5e5 109 Master Poster

I actually got it working with code that is quite similar (nested select statements with grouping and counting). Although I don't think the line 'course_code' would work in your query.

Oops. You are correct. I had created a table called 'course_code' with your intermediate results as a short cut while I was experimenting. Anyway, I'm glad you came up with something that works.

d5e5 109 Master Poster

For your first question, try this (not tested)

SELECT course, cnt
FROM (
SELECT course, count( * ) AS cnt
FROM uniresults
WHERE symbol = 'F'
GROUP BY course) `b`
WHERE cnt = (
SELECT min( cnt )
FROM `course_count`
)
d5e5 109 Master Poster

Pretend your subquery in parentheses is just another table. Give it an alias by putting a name after it (in my example I used `a` as an alias.) Your ORDER BY for your main query (which contains the subquery) goes at the end. Something like this:

SELECT x, y, z
FROM (
SELECT *
FROM `tbl_address`
WHERE retrieved <>1
LIMIT 0 , 2
) `a`
ORDER BY z
d5e5 109 Master Poster

If you really need spaces in the binary string, you can add them like this:

#!/usr/bin/perl
use strict;
use warnings;
my %h;
while(<DATA>){
        chomp;
        my $bin=sprintf '%016b', hex($_);
        my @groups = $bin =~ m/(\d{4})(\d{4})(\d{4})(\d{4})/g;
        print "$_ - " . join(' ', @groups) . "\n";
}

__DATA__
0x0001
0x0002
0x0003
0x0004
0x0005
0x0006
0xFFFF

That gives you the following output

0x0001 - 0000 0000 0000 0001
0x0002 - 0000 0000 0000 0010
0x0003 - 0000 0000 0000 0011
0x0004 - 0000 0000 0000 0100
0x0005 - 0000 0000 0000 0101
0x0006 - 0000 0000 0000 0110
0xFFFF - 1111 1111 1111 1111
d5e5 109 Master Poster

I need to take specific actions depending on the number of 1's in the 16bit binary string.

I want to make sure I understand this requirement correctly. You mean that you would take the same action for 0x0003 as you would for 0x0005, because the binary strings that correspond to them both contain two 1's? If so, your script could count the ones something like this:

#!/usr/bin/perl
#count_ones_in_hex.pl
use strict;
use warnings;

while(<DATA>){
        chomp;
    my $bin=sprintf '%016b', hex($_);
        my $count_ones = my @ones = $bin =~ m/1/g;
    print "$bin has $count_ones one(s)\n";
}

__DATA__
0x0001
0x0002
0x0003
0x0004
0x0005
0x0006
0xFFFF
d5e5 109 Master Poster

I tried as u said .. it worked .. But now, how can I display data in tabular form together with the titles .. and the border ...

archik123 started this thread on the subject of removing delimiter from data. Please start a new thread to ask your question about displaying data in an html table. That is a separate topic and it would be confusing to ask a new question on page 3 of archik123's thread.:)

d5e5 109 Master Poster

After assigning the values to $savestring and before writing $savestring to the file, try adding the following two statements:

$savestring = str_replace("\r", '', $savestring);
$savestring = str_replace("\n", '', $savestring);
d5e5 109 Master Poster

I don't understand why you need to convert the hex number into binary before using it to make a decision. Are these two separate requirements? You need to convert the string to binary AND you need to test the value and take one of 255 possible actions?

For your first question, there appears to be a solution that does something close to what you want here but I don't know how to break the resulting string into 4-character pieces separated by spaces.

For your second question: using a hash can often serve as an alternative to a long if-else-if statement. You could build a hash with 255 key-value pairs where the value is either a reference to a named subroutine or a string representing a block of code which you can eval() . The key of one of the hash entries would correspond with the string you read from the file. I mean something like the following:

#!/usr/bin/perl
use strict;
use warnings;
my %h; #Hash to store 255 (slightly) different pieces of perl code

foreach(0x1..0xFFFF){
    $h{$_} = qq(print 'Let us decide to take action number ', $_, "\n");
}

while (<DATA>){
    chomp;
    eval($h{hex($_)});
}
__DATA__
0x0009
0x0004
0x0007
0x00AA
0xFFFF

This gives the following output:

Let us decide to take action number 9
Let us decide to take action number 4
Let us decide to take action number 7
Let us decide to take action number 170
Let us decide to take action number …
d5e5 109 Master Poster

I would suggest an easier approach than the one you are taking. Read the file one line at a time. Take the first three characters at the beginning of each line and concatenate them all in one variable, so you will end up with a variable having the value 'ABCXYZMNOPODNFYPORLKMABCXYZMNOEFGNFYPORLKMABCXYZMNOABCXYZMNOEFG' .

Now you want to know the number of times the pattern 'ABCXYZMNO' occurs in the string and the number of times 'ABCXYZMNOEFG' occurs. Using regex you can find all matches of a pattern in a string more easily than trying to do it while looping through a file.

d5e5 109 Master Poster

Could you post the contents of your formda1.txt file here, between [code] paste exact contents of file here [/code] tags please? When you say the line appears broken in two, I think maybe your text editor is just wrapping it. Do you have a way to view the End Of Line characters? I don't see how your script is inserting newline characters in your string. If your data line doesn't contain newline characters, and only appears to because your text editor has word-wrap enabled, then there is nothing to fix (except to get a better text editor, so that you can set word-wrap to 'off').

d5e5 109 Master Poster

One more thing ..what if i want to merge the first 3 cols data into one cell ..

i have used COLSPAN=3 in <th> ..but it is not working ...

what should be modified? to have the merging of first 3 cells into one ...

Before experimenting further with your php scripts, I think a good approach to designing your page would be to create what you want to see as a static html page first, using one row of sample data having the maximum number of expected characters in each column. That would be easier to work with. Once you have an html page that displays the one sample row nicely, you can use this page as a model for creating your php page, including your script to read the text file and dynamically build the table rows.

So far, many of your questions, such as how to set the table border, merge columns, fit all the headers on the page, etc. pertain to HTML and CSS. You may get better responses to those questions on the HTML and CSS forum.

d5e5 109 Master Poster

More difficult than I thought. Try something like this.

<html>
    <body>
        
<?php
//Build an array of column headers
$hdr[] = 'Fname';
$hdr[] = 'Mname';
$hdr[] = 'Lname';
$hdr[] = 'etc.';
$hdr[] = 'etc.';
$hdr[] = 'etc.';
$hdr[] = 'etc.';
$hdr[] = 'etc.';
$hdr[] = 'Sex';
$hdr[] = 'Date of Birth';
$hdr[] = 'etc.';
$hdr[] = 'Experience';

//Create a new array of data with elements corresponding to column headers
$disp = array();
$file_handle = fopen("/home/david/Programming/apache/httpd/formda.txt", "r");
while (!feof($file_handle)) {
    $line = fgets($file_handle);
    $chunks = explode('||', $line);//Remove delimiters and put data into an array
    $bdate = $chunks[9] . ' ' . $chunks[10] . ', ' . $chunks[11];
    array_splice($disp, count($disp), 0, array_slice($chunks,0,8));
    array_push($disp, $bdate);
    $disp = array_merge($disp, array_slice($chunks,12,2));
}
fclose($file_handle);

//print_r($disp);
$startrow = 0;
$endrow = 0;
echo '<table>';
echo '<tr>';
foreach ($hdr as $h){
    echo '<th>';
    echo $h;
    echo '</th>';
}
echo '<tr>';

foreach($disp as $index=>$data){
    $endrow = 1;
    if ($index % 11 == 0){
        $startrow = 1;
        $endrow = 0;
        echo '</tr><tr>';
    }
    echo '<td>';
    echo $data;
    echo '</td>';
    //if ($index % 11 == 0 && $endrow == 1){
    //    $startrow = 0;
    //    echo '</tr>';
    //}
}
echo '</table>';
?>

    </body>
</html>
d5e5 109 Master Poster

But if the client disabled the javascript you will have to validate it with PHP or it can couse bad info saving !

Right. One downside to javascript or any other client-side scripting is that the user may have configured his or her browser not to run scripts. When you study javascript, you will learn how to design your page to take into account what a user will see if javascript is disabled: either an alternative (no-frills) way of posting the data and having it validated on the server (by PHP or some other server-scripting language), or just a message telling the user to enable javascript on their computer if they want to use your web-site.

Another point about javascript is the user can view the page source and see your javascript scripts, copy some of your coding techniques and gain an undeserved reputation as a great javascript programmer.:) (I've never had to worry about that.) Whereas the user can't see scripts that run on the server, such as PHP scripts.

d5e5 109 Master Poster

PHP runs on the server so before it can respond to what the user enters in the browser, which runs on the client, the client must post something to the server.

Javascript runs in your browser on the client, so it can respond to events such as the user typing data, clicking mouse, moving mouse pointer over an object, etc. independently of what or when data is posted to the server.

d5e5 109 Master Poster
<html>
    <body>
<?php
$contents = 'john||mk||mlm||klm||lkm||lkm||lmlk||mkl||female||January||9||2004||ljnbjknjlnln||Expert||';
$chunks = explode('||', $contents);

foreach($chunks as $chunk){
    print $chunk . '<br />';
}
?>
    </body>
</html>

Sure you can also put it in tabular format. I don't know how many columns you want.

d5e5 109 Master Poster

You already open("exercise1.txt", "w") outside your loop. This creates a new empty file. Good. But you also open the same file in your for loop. Don't do that. Repeating the open statement in 'w' mode for that file recreates the empty output file each time it reads a line from your input file, thus erasing any content you have written to it.

d5e5 109 Master Poster

What is your current working directory when you are running the program? To find out, run the following commands from whatever editor you are going to use to test your program.

import os
print os.getcwd()

I suspect that you don't have all the necessary permissions to create and write to a file in the current working directory when you get the IO error. You can avoid the problem by including the path to a directory where you know you can create and update files, in your filename, like this:

>>> test = open('/home/david/Programming/Python/Test.txt', 'w')
>>> test.write('Hi there!')
>>> test.close()
>>>
d5e5 109 Master Poster

The error is merely a symptom of the wider problem. The problem is the reader treating the carriage control/line feed as a new record in the middle of reading a record of a set number of fields.

Yes, I understand now. The reader interprets carriage control/linefeed as end-of-line characters, which results in the rest of the fields for that record having value of None. Your program expects these fields to have values other than None so errors result.

It would be good if there was a way to tell the csv module that the value of end-of-line character is not the usual CR/LF but the docs say it is hardcoded.

The reader is hard-coded to recognise either '\r' or '\n' as end-of-line, and ignores lineterminator. This behavior may change in the future.

I guess your options include rolling your own parser, as woooee suggests, or pre-processing the file by reading it, removing all the CR/LF characters and writing it to a new file that you will use as input for the csv parsing.

d5e5 109 Master Poster

Hello,

I am learning perl programming but my problem is iam unable to find how the functions, commands,loops & conditions are working in a programme can anyone help me how to write a programme? what is the logic?

What is the logic? For example, here is a statement that contains a condition:

If we could write better tutorials than you can find already HERE and we had the time then we could answer your question.:)

Start writing and running short, simple programs first. If one of your programs doesn't work, post the shortest, simplest version of your code here, enclosed in [code] Your code goes here [/code] tags and tell us what output you expected to get, and what output you got instead. If we can reproduce the error simply we may be able to help.

d5e5 109 Master Poster

The error occurs if you call your FormatDate function with a parameter having a value of None. I don't see a relation to the presence or absence of newline characters.

>>> def FormatDate(date):
      return date[6:10] +"-" +date[3:5] + "-" +date[0:2]

>>> FormatDate('12/10/2010') #Try it with text representing a date
'2010-10-12'
>>> 
>>> FormatDate(None) #What if the parameter has no value?
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    FormatDate(None) #What if the parameter has no value?
  File "<pyshell#1>", line 2, in FormatDate
    return date[6:10] +"-" +date[3:5] + "-" +date[0:2]
TypeError: 'NoneType' object is unsubscriptable
>>>
d5e5 109 Master Poster

I failed to replicate the error running your script on the data you posted.

It looks like you have Python version 2.6. I do too (2.6.4 to be exact) so I guess the problem isn't different versions. (Maybe different versions of the csv module?)

Also, posting data in quote tags may not preserve the format. Maybe if you attach the data file to your post or post it between code tags we can reproduce the error.

d5e5 109 Master Poster

Yes, it replaces only the specified string in the specified column. Forward slashes in other columns won't change.

d5e5 109 Master Poster

I'm not sure that answering a question after 5 years is really effective.

system("sleep 157784630s");#Wait 5 years Note: I haven't had time to test this.:)

d5e5 109 Master Poster

For a table named 'items':

update items set itemName = replace(itemName,'/','');
d5e5 109 Master Poster

No, views don't take up much space. The data are in the tables. Views are not much more than saved select statements plus some optional aliases of input and output columns, I think.

By 'cluttering' I meant we had many programmers creating views publicly available to everybody. It got tedious browsing through all the available names of views, some of them unused or redundant. This is not a downside specific to views. The more database objects you create that are dependant on each other, the more important it becomes to keep track of them and their relationships.

d5e5 109 Master Poster

I've seen that done a lot querying an Oracle database where I used to work. It worked fine. I haven't tried that in MySQL but I can't think of any reason that it wouldn't work.

Just keep in mind that if you do this a lot you may end up with a lot of views depending on a lot of views. If you want to change or delete some of these views (as in "let's do a clean-up") you need to remember which views depend on the views you want to change. I remember we had a lot of old views cluttering our database that nobody wanted to delete in case some report, procedure or other view used them. We finally had to get our act together and remove the unused views.

d5e5 109 Master Poster

Python has several kinds of data structures, including lists, tuples, sets, and dictionaries. A dictionary associates unique keys with values and is good for retrieving the value stored for any specific key.

>>> lights = {'red': 'stop', 'green': 'go', 'yellow': 'go like hell'}
>>> print 'red means ' + lights['red']
red means stop
d5e5 109 Master Poster

You want all the lines containing the literal 'STRING' plus only two of the lines containing the literal 'INTEGER'? Here is how you could match the lines you want using a regex pattern.

#!/usr/bin/env python
import re

#You didn't say what rule you had in mind
#when you chose only the last two lines containing 'INTEGER'
#so the following pattern represents my guess
pattern = r'(STRING:.+)|(5\.1537\.(2|3) = INTEGER: \d)$'

for line in open('/home/david/Programming/Python/data.txt'):
    match = re.search(pattern, line)
    if match:
        print line.rstrip()

This gives the following output.

.1.3.6.1.2.1.25.3.7.1.2.1537.1 = STRING: "/dev/hdb1"
.1.3.6.1.2.1.25.3.7.1.2.1537.2 = STRING: "/dev/hdb2"
.1.3.6.1.2.1.25.3.7.1.2.1537.3 = STRING: "/dev/hdb3"
.1.3.6.1.2.1.25.3.7.1.3.1537.1 = STRING: "0x341"
.1.3.6.1.2.1.25.3.7.1.3.1537.2 = STRING: "0x342"
.1.3.6.1.2.1.25.3.7.1.3.1537.3 = STRING: "0x343"
.1.3.6.1.2.1.25.3.7.1.5.1537.2 = INTEGER: 3
.1.3.6.1.2.1.25.3.7.1.5.1537.3 = INTEGER: 0
d5e5 109 Master Poster

How about attaching a sample file and telling us what part of the data you want to extract? That way those of us who are not network engineers might understand what you want to do. For example, does your file contain data like the following?

.1.3.6.1.2.1.25.3.7.1.1.1537.1 = INTEGER: 1
.1.3.6.1.2.1.25.3.7.1.1.1537.2 = INTEGER: 2
.1.3.6.1.2.1.25.3.7.1.1.1537.3 = INTEGER: 3
.1.3.6.1.2.1.25.3.7.1.2.1537.1 = STRING: "/dev/hdb1"
.1.3.6.1.2.1.25.3.7.1.2.1537.2 = STRING: "/dev/hdb2"
.1.3.6.1.2.1.25.3.7.1.2.1537.3 = STRING: "/dev/hdb3"
.1.3.6.1.2.1.25.3.7.1.3.1537.1 = STRING: "0x341"
.1.3.6.1.2.1.25.3.7.1.3.1537.2 = STRING: "0x342"
.1.3.6.1.2.1.25.3.7.1.3.1537.3 = STRING: "0x343"
.1.3.6.1.2.1.25.3.7.1.4.1537.1 = INTEGER: 14877060 KBytes
.1.3.6.1.2.1.25.3.7.1.4.1537.2 = INTEGER: 9920624 KBytes
.1.3.6.1.2.1.25.3.7.1.4.1537.3 = INTEGER: 0 KBytes
.1.3.6.1.2.1.25.3.7.1.5.1537.1 = INTEGER: 1
.1.3.6.1.2.1.25.3.7.1.5.1537.2 = INTEGER: 3
.1.3.6.1.2.1.25.3.7.1.5.1537.3 = INTEGER: 0

I copied that from http://www.unleashnetworks.com/resources/articles/95-work-with-output-from-snmpwalk.html but I don't know what portion of the file you want to extract.

d5e5 109 Master Poster

I found this incredibly difficult as I've done very little XML. I tried using XPath but don't know enough about XPath. Finally, I tried XML::Simple.

#!/usr/bin/perl
#parse_xml_simple.pl
use strict;
use warnings;

# use module
use XML::Simple;

# create object
my $xml = new XML::Simple;

# read XML file
my $file = '/home/david/Programming/Perl/data/Aj.xml';
my $data = $xml->XMLin($file,
                        ForceArray => 1,
                        KeyAttr    => {},
                      );

my %count;
foreach my $article (@{$data->{article}}) {
    my $year = $article->{cpyrt}->[0]->{cpyrtdate}->[0]->{date};
    my $author = $article->{authgrp}->[0]->{author}->[0];
    my $autname;
    
    foreach ( keys %{$author} ){
        $autname .= $$author{$_}->[0];
    }

    $count{$year}->{$autname}++ if defined($autname);
}

foreach (keys %count){
    my $ctr = keys %{$count{$_}};
    print "$_ $ctr\n"
}

This gives the following output:

1913 3
1917 2
d5e5 109 Master Poster

Yes, it works for me after making the change Mike suggested. It keeps the userName after I click on various letters.

Does it lose its value for you the first time you click a letter, or only after you click a specific sequence of letters?

You appear to have an elusive run-time bug that occurs only sporadically. I don't know how to fix it, but I do recommend you add use strict; near the start of your perl script. It will cause several error messages that you can fix by declaring your variables and not using bare words for letters. In the process of satisfying the requirements of the strict module you may solve your problem, or not. But your instructor would probably agree that you should use strict for any non-trivial program.

"You should use the strict pragma for any Perl script more than a few lines long, and for all CGI scripts."