d5e5 109 Master Poster

You could alter your SELECT statement to explicitly name the columns you want in your result set (instead of *) and include a calculated column which you would specify something like this:

SELECT order.item_name, order.quantity, item.price, order.quantity*item.price AS value 
FROM fb.order
LEFT JOIN item  on
	order.item_name = item.item_name
WHERE fb.order.order_status = 'Served' and tab_name='A'

(But then in PHP you would need to accumulate the value for each row in a variable to get your total value.)

BTW maybe it's not a good idea to name your table 'order' because it is a MySQL reserved word.

d5e5 109 Master Poster

Regarding doubt #3, I think you would have to write conditional logic to allow the -r (rename) parameter only if the -d (directory) parameter is specified. Maybe roughly like the following:

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

use Getopt::Long;
 
my ($help, @dir, @rename_to);
 
#-- prints usage if there is an unknown
#   parameter or help option is passed
usage() if ( ! GetOptions('help|?' => \$help, 'd:s' => \@dir, 'r:s' => \@rename_to)
         or defined $help );

if (@rename_to > 0 and @dir < 1){
    die "-r option specified without -d option.\n"
        . "If -d not specified, -r is not allowed.\n"
        . "If you don't eat your meat, you can't have any pudding!\n"
}

sub usage
{
  print "Unknown option: @_\n" if ( @_ );
  print "usage: program [-d DIRECTORY_NAME] [-r NEW_DIRECTORY_NAME] [--help|-?]\n";
  exit;
}
d5e5 109 Master Poster

That solution is slightly more efficient than mine, although I'm not sure it matters much in such a fast-completing script :)

Yes, I agree, if the OP is using this in a larger project, printing ten even numbers is not going to be one of the bottlenecks.

I just skimmed through an article that has a gripping title -- Optimization: Your Worst Enemy -- explaining why programmers should optimise only when necessary to solve performance problems.

d5e5 109 Master Poster

It's good to show one of the loop solutions too, as you did, since the OP said he was new to Perl. When I started with Perl, solutions using the map function seemed hard to read. This was the first time I found a good use for map so of course I wanted to show it off.:)

But using a loop can be easier to understand. Here's a minor variation on the loop approach.

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

for (my $n = 2; $n < 21; $n += 2){
    print "$n\n";
}
d5e5 109 Master Poster

Nice one, mitchems. Another way would be

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

my @evens;
my $n = 0;
my $number_to_give_up_at = 100;
# $#evens will contain value of index of last element in @evens array
while ($n++ < $number_to_give_up_at and $#evens < 9){
    push @evens, $n if $n % 2 == 0;
}
print join("\n", @evens);

Spakes, please mark it solved so we can stop working on this.

d5e5 109 Master Poster

You're welcome. To understand how that works you need to know the shortcut for building a range of numbers, (lowest number followed by two dots followed by largest number, all within parentheses) which results in an array of sequential numbers, in increments of one. Plus you need to know the map function, which performs whatever function or statement you specify on each member of the array or list you specify.

There are other ways of doing the same thing, such as using some kind of loop.

d5e5 109 Master Poster

Hi ,

How do I write a code that will print the first 10 even numbers in PERL

Thank you

Here is one way:

#!/usr/bin/perl
use strict;
use warnings;
map {print $_ * 2 . "\n"} (1..10);
d5e5 109 Master Poster

Are you sure $contents contains the string you say it does? When I manually assign the string you want to match to $contents the match works and there is something in the $out array.

<?php
$contents = <<<END
<a href="./viewtopic.php?f=15&amp;t=119871" class="topictitle">Twilight Graphic Novel</a>
END;
preg_match_all("/<a href=\".\/(viewtopic.php\?f=15&amp;t=[0-9]+)\" class=\"topictitle\">([#\w\s_\-!$%&()?.,'\":;{}\/\\|’=\[\]+\–\™ ]+)<\/a>/i",$contents,$out);

$len=count($out[0]);
echo '$len is equal to ' . "$len\n";
print_r($out);

//Gives the following output:
//$len is equal to 1
//Array
//(
//    [0] => Array
//        (
//            [0] => <a href="./viewtopic.php?f=15&amp;t=119871" class="topictitle">Twilight Graphic Novel</a>
//        )
//
//    [1] => Array
//        (
//            [0] => viewtopic.php?f=15&amp;t=119871
//        )
//
//    [2] => Array
//        (
//            [0] => Twilight Graphic Novel
//        )
//
//)
?>
d5e5 109 Master Poster

Is it too late to change the design of the 'children' table? Your problem comes from there.

Why not have only two columns? One column would identify the user and the other the name of one child. Each user could have as many rows in the children table as needed to identify all that user's children. If you must enforce a maximum of four children per user you could do that in your program logic. But a one-many relation between the user table and the children table would give you more flexibility than your actual design, in my opinion.

d5e5 109 Master Poster

Apparently, part of the problem starts at this statement: @arr=split("",$_); #This splits the string into single characters To test, I ran the following:

print join("\n",split("",'abcdefghijklmno'));

And the output was

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o

I know that doesn't help much. If nobody else figures out how to do it, I'll have another look when there's time.

d5e5 109 Master Poster

Here is an example of how to find differences between an older and newer file, using a hash. For simplicity I used ordinary text data, but it should work for csv files as well since you don't need to parse the lines into fields at this point. (You can parse the data with another script, later.)

I attached the data files, 'names_1.txt' and 'names_2.txt' to this post.

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

my $dir = '/home/david/Programming/Perl/data';
my $f1 = "$dir/names_1.txt";
my $f2 = "$dir/names_2.txt";
open FILE1, "$f1" or die "Could not open $f1: $! \n";

my %results = ();#Hash to store lines from files
my %meaning = (-1, "In new file but not in old file",
               0, "In both new and old files",
               1, "In old file but not in new file",); #Hash associating values with statuses

while(my $line = <FILE1>){
    chomp $line;
    $results{$line}=1;
}
close(FILE1);

open FILE2, "$f2" or die "Could not open $f2: $! \n";
while(my $line =<FILE2>) {
    chomp $line;
    #$results{$line}++; #Instead of incrementing by one...
    $results{$line}--; #Instead of incrementing by one...
}
close(FILE2);

foreach(sort order keys %results){
    print "Key $_ has value $results{$_} which means $meaning{$results{$_}}\n";
}

sub order{
    $results{$a} <=> $results{$b};
}
d5e5 109 Master Poster

I pasted some text into the __DATA__ section at the end of my script for convenience but the following will work just as well if you read from a real text file.

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

sub is_separator {
    my $line = shift; #Assign passed argument to variable
    if ($line =~ m{^\/\/(\*)+}) {
        return 1; #Return true value
    }
    else{
        return 0; #Return false value
    }
}

while (<DATA>){
    if (is_separator($_)){
        print "Line number $. is a separator.\n";
    }else{
        print "Line number $. is not a separator.\n";
    }
}
__DATA__
Last year, I was based in Sidney while exploring the surrounding Saanich Peninsula’s emerging foodie culture — nascent vineyards and cideries, family enterprises making handcrafted gin and raw chocolate. But I was also pleasantly surprised to discover Sidney’s other angle: Inspired by Hay-on-Wye, the medieval Welsh town known for its many secondhand and antiquarian bookstores, Sidney,  population 11,000, is a bibliophile’s paradise — with no fewer than 12 independent specialty bookstores. There are rare, collectible and bargain books, with topics ranging from military history to gardening. And, yes, there are enough Stieg Larssons to go around.
//*********************************************
Since then, I have been wanting to return and get lost in these shops, perhaps even discuss a book or two over oyster burgers with some literary pals.
Indeed, Sidney seemed like the perfect place for a book club getaway. There is a new hotel, the Sidney Pier, a sleek seaside property with a restaurant that serves inspired local food …
d5e5 109 Master Poster

Sorry for another regex post but i have been trying to get a regex to work to check for unwanted characters in a string like @#?! I have tried

var cityreg=/^[^$%@!]+$/;

but it doesn't seem to work?

You need to assign the regex pattern object to a variable and then use the test method of the regex object to check the input you pass to it.

function check()
{
    var text=prompt("Please enter some text","Harry Potter");
    var clean=/^[^$%@!]+$/; //Define your regex pattern
    if (text!=null && text!=""){
      if (clean.test(text)){ //Use your regex pattern to test input and return true or false
        alert(text + " is OK.")
      }else{
        alert(text + " contains an invalid character.")
      }
    }
}
d5e5 109 Master Poster
>>> line_of_numbers = "5 7 6 35 346 245"
>>> list_of_numbers = line_of_numbers.split()
>>> print list_of_numbers
['5', '7', '6', '35', '346', '245']
>>>
d5e5 109 Master Poster

For really simple html you can use regular expressions. For more complex data it would be better to search CPAN for a good html parser module and learn how to use it (which I haven't got around to doing yet). Meanwhile the following script should do what you want.

#!/usr/bin/perl
#ParseList.pl
use strict;
use warnings;
open my $fh, '<', '/home/david/Programming/Perl/data/list.txt';
my @list;
while (<$fh>){
    m/href="(\w+\.\w+)"/;
    push @list, $1;
}
print "Here is the list:\n";
print join(", ", @list);
d5e5 109 Master Poster

Something has changed in the convert subroutine in the last couple of scripts you posted.

##my $mem = $_; #This does not contain the argument passed to the sub
my $mem = $_[0]; #The first (and only) element in the array of args, @_

When I run the following script, which reads the attached file, I get the attached output file. (If, by chance, this version of the script works for you, then there's no need to send us your data files. Otherwise, please attach your input file and we'll have look at it.)

#!/usr/bin/perl
#TextCSVBastienP.pl
use strict;
use warnings;
use diagnostics;
#use Encode qw( _utf8_on );
#binmode STDOUT, ":utf8";
my $dir = '/home/david/Programming/Perl/data';
my $in = $dir . '/' . '1.csv.txt'; #Added .txt in order to attach files to post
my $out = $dir . '/' . 'out.csv.txt';#Daniweb requires .txt extension to attach 
#open(INFILE,"<:raw:encoding(utf-16):crlf:utf8", "1.csv");
open(INFILE, '<', $in);
open(OUTFILE, '>', $out);
while(<INFILE>)
{
	my $rec = $_;
	chomp($rec);
	$rec =~ s/X'([a-fA-F0-9]+)'/convert($1)/eg;
        print OUTFILE "$rec\n";
}
close(INFILE);
close(OUTFILE);

sub convert{
    #This subroutine contains Mike's regex to substitute hex digits with
    #the corresponding characters
    my $mem = $_[0]; #The first (and only) element in the array of args, @_
    $mem =~ s/0d0a//; #Remove 0d0a from string of hex digits
    $mem=~s/([a-fA-F0-9]{2})/chr(hex $1)/eg;
    chomp $mem;
    return $mem;
}
BastienP commented: As usual, a very helpful post :-) +1
d5e5 109 Master Poster
#!/usr/bin/perl
use strict;
use warnings;

#For testing, let's assign a string constructed with q(), which puts single
#quotes around text that may contain quotes. You can read from your file instead.
my $rec = q("CN=BERRY Richard,OU=TestFinance,OU=HR,OU=CORP,OU=CR,DC=mycorp,DC=com","BERRY Richard",BERRY,FR,"Puylouvier",FRANCE,,56000,"+33 1 23 45 67 89","+ 33 1 23 45 67 80",Richard,FRANCE,IT,X'332c206176656e7565204e6577746f6e0d0a',Bob.Malone,Richard.BERRY@mycorp.net," -",);
#Remove X and ticks, call convert subroutine with data from between the ticks
#Substitute with string returned from convert subroutine.
$rec =~ s/X'([a-fA-F0-9]+)'/convert($1)/eg;
print $rec;

sub convert{
    #This subroutine contains Mike's regex to substitute hex digits with
    #the corresponding characters
    my $mem = $_[0];
    $mem =~ s/0d0a//; #Remove 0d0a from string of hex digits
    $mem=~s/([a-fA-F0-9]{2})/chr(hex $1)/eg;
    chomp $mem;
    return $mem;
}
d5e5 109 Master Poster

I haven't figured out how to do this yet but the solution may involve something called Fork, which is a way of starting up a copy of your program that knows that it is a copy (i.e. not the parent) and can do something independently and somehow communicate back to the parent that the task has been accomplished. It couldn't hurt to read this short python fork example

d5e5 109 Master Poster

I'm not sure why you need an infinite loop but maybe you want to wrap the sendIP() in a try block. The finally block will quit the server whether or not your sendIP() succeeds or causes an exception.

#!/usr/bin/env python
# This is the loop i need to break. I know there will be another problem with the sleep() :
while 1:
    try:
        sendIP()
        time.sleep(25000)
    finally: #The following statements run whether or not an exception occurs
        print "Connection Closed.."
        server.quit()
        break
d5e5 109 Master Poster

Yes, this site was down part of yesterday afternoon. Since this thread hasn't been marked solved yet, here's one more approach:

#!/usr/bin/env python
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    labels = []
    values = []
    save_next = False
    def handle_data(self, *args):
        s, = args
        if MyHTMLParser.save_next:
            MyHTMLParser.values.append(s)
            MyHTMLParser.save_next = False

        if str(args).find("Allowance") > 0:
            MyHTMLParser.labels.append(s)
            MyHTMLParser.save_next = True

#Assign web page contents to htmlstring (Snipped from post to save space)        
htmlstring = """<Please paste webpage content here>"""

h = MyHTMLParser()
h.feed(htmlstring)
h.close()

for i in range(1, 5):
    print "%30s:%15s" % (h.labels[i], h.values[i])
d5e5 109 Master Poster

If you stick with the regular expressions approach, the following should return the full time (hh:mm:ss).

rawstr = r"""Time Until Allowance Refill</td><td style="border-width:0px;">\s*(?P<Refill_Time>\d+:\d+:\d+)\D"""

In regular expressions \d+ means "one or more consecutive digits", so \d+:\d+:\d+)\D means "one or more consecutive digits followed by a colon followed by ... etc." and the \D represents any character that is not a digit. Only the portion matched by the pattern between the parentheses belongs to the group which gives you the data you want (hopefully).

d5e5 109 Master Poster

Kodos The Python Regex Debugger suggests the following ways to find Plan Allowance value.

#!/usr/bin/env python
import re
rawstr = r"""Plan Allowance \(MB\)</td><td style="border-width:0px;">\s*(?P<Plan_Allowance>\d+)\D"""
embedded_rawstr = r"""Plan Allowance \(MB\)</td><td style="border-width:0px;">\s*(?P<Plan_Allowance>\d+)\D"""
matchstr = """<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head>
<meta http-equiv="refresh" Content="60;url=/stlui/user/allowance_request.html">
<title>Download Allowance Status</title></head><body><h3 style="font-size: 150%; color:blue; text-align:center; font-weight:bold">DOWNLOAD ALLOWANCE STATUS</h3><TABLE width='100%' cellpadding='10'><tr><td style="text-align:center;"><h3>Usage within allowance - no download restrictions</h3></td><td><span style="display:block;text-align:center">100%</span><table style="font-size:1; background-color:white; border:1px solid black;" width='15%' cellspacing='0' cellpadding='0' align='center'><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr><tr style="background-color:green"><td>&nbsp;</td></tr></table><span style="display:block;text-align:center">0%</span></td></tr><tr><td>&nbsp;</td><td><table style="font-size:18; border-width:0px;" width=90% cellspacing=0 cellpadding=0 ALIGN=CENTER><tr><td>&nbsp;</td><td style="border-width:0px;">Plan Allowance (MB)</td><td style="border-width:0px;"> 625</td></tr><tr><td>&nbsp;</td><td style="border-width:0px;">Allowance Remaining (MB)</td><td style="border-width:0px;"> 625</td></tr><tr><td><span style="background-color: green;">&nbsp;&nbsp;&nbsp;</span>&nbsp;</td><td style="border-width:0px;">Allowance Remaining (%)</td><td style="border-width:0px;"> 100</td></tr><tr><td>&nbsp;</td><td style="border-width:0px;">Time Until Allowance Refill</td><td style="border-width:0px;"> 22:18:01</td></tr></table></td></tr></TABLE>
</body>
</html>"""

# method 1: using a compile object
compile_obj = re.compile(rawstr)
match_obj = compile_obj.search(matchstr)

# method 2: using search function (w/ external flags)
match_obj = re.search(rawstr, matchstr)

# method 3: using search function (w/ embedded flags)
match_obj = re.search(embedded_rawstr, matchstr)

# Retrieve group(s) from …
d5e5 109 Master Poster

What was the error that you saw in the terminal? If an error other than IOError, UnicodeDecodeError or SyntaxError occurs (if that is possible?) then I think (haven't tested it) control would go to your else block which reports success.

d5e5 109 Master Poster

What are the names of your input files? Before you run your program you have 10 files. After you run it you will have 20 (10 input plus the 10 new output files). If you run your program more than once, the program will need to specify the names of the files it needs to read, since you won't want to read the output files as well.

I recommend you name your input files according to an easily recognisable pattern, such as, "in_001.txt", "in_002.txt" etc. Then your program can make an array of file names to read, and as it opens each file it can open a new output file named something like "out_001.txt", "out_002.txt" etc.

d5e5 109 Master Poster

One more thing... looking at mitchems' version, now that the loop counter is renamed $n instead of $x, I think the following line: my $f = "$cur_dir/xyz_channel_$x\.dat"; should be replaced by: my $f = "$cur_dir/xyz_channel_$n\.dat"; #$n is the file counter

d5e5 109 Master Poster

I can't explain what is going on in Windows, but from what you say it seems the solution is to have your program get and use the absolute path joined with the filename. The following should work on both platforms:

#!/usr/bin/env python
import webbrowser
import os
abs_path = os.path.abspath('.') #Absolute path of current working directory
filename = os.path.join(abs_path, 'index.html')
print 'Try to open ' + filename
webbrowser.open(filename)
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. Also when you say it didn't work, do you mean that you got no output, or that the output was not what you wanted? If you got some output please show us what it looked like.

d5e5 109 Master Poster

OK, I'll try that.

One more question: I want to open a local file with the browser. Is it possible to use arelative path? I wouldn't know where the user places the folder, so the path to the html file has to be relative.

I tried opening the file using the absolute path, then finding out my current working directory and opening the file with a path relative to it, then changing the cwd to the file location and opening the file by name only. It all works, on Linux anyway.

>>> import webbrowser
>>> webbrowser.open('/home/david/Programming/Python/index.html')
True
>>> import os
>>> os.getcwd()
'/home/david'
>>> webbrowser.open('Programming/Python/index.html')
True
>>> os.chdir('Programming/Python')
>>> webbrowser.open('index.html')
True
>>>
d5e5 109 Master Poster

Oh, wait, it's not completely solved:

on linux, everything is fine.

on windows, however, webbrowser.open only opens Explorer, even though firefox is the default.

If I try startfile, it does open the associated program as d5e5 explained, but it fails to open the help file (it seems it only works with URL's)

I tried the following

>>> import webbrowser
>>> webbrowser.open('c:\Users\David\Programming\Javascript\CHAPTERS\ch 08\index.htm')
True
>>>

on Windows Vista Home Premium and it opened the file in my default browser, which is Chrome. In Linux it opened in Firefox, which is my default browser for Linux. I don't know why webbrowser is using Explorer on your computer when it is not the default. (Maybe your version of Windows or Explorer is different than mine?) Have you tried the following?

>>> webbrowser.get("windows-default").open('c:\Users\David\Programming\Javascript\CHAPTERS\ch 08\index.htm')
True
>>>
d5e5 109 Master Poster

Hi
Velocity is not related to file no., it is something which starts at some random value and increases with constant step and ends at some value. Of course (end value-start value)/step value is no. of my files xyz_channel_*.dat. I just want that velocity should be printed from start to end; parallel to the 'diff' value starting for xyz_channel_1.dat file and ending with xyz_channel_200.dat.

So in total there is two problem, 1st problem is for velocity, it prints a constant value "6"..... but i want it step increase, for example..

my $velocity;
for ($velocity=6.659; $velocity=14.659; $velocity=$velocity+0.04){
print "$velocity \n";
}

and second problem is sorting the files for calculation.... it is sorting but not not in numerical order.
...
..
see the output,....which i get

6                 3 from /data/shuklax/xyz_channel/xyz_channel_1.dat
6                -3 from /data/shuklax/xyz_channel/xyz_channel_10.dat
6               -13 from /data/shuklax/xyz_channel/xyz_channel_100.dat
6                -9 from /data/shuklax/xyz_channel/xyz_channel_101.dat
6                 6 from /data/shuklax/xyz_channel/xyz_channel_102.dat
6                -5 from /data/shuklax/xyz_channel/xyz_channel_103.dat
6               -17 from /data/shuklax/xyz_channel/xyz_channel_104.dat
6               -11 from /data/shuklax/xyz_channel/xyz_channel_105.dat
6               -16 from /data/shuklax/xyz_channel/xyz_channel_106.dat
6                -9 from /data/shuklax/xyz_channel/xyz_channel_107.dat
6                -1 from /data/shuklax/xyz_channel/xyz_channel_108.dat
6                -7 from /data/shuklax/xyz_channel/xyz_channel_109.dat
6               -15 from /data/shuklax/xyz_channel/xyz_channel_11.dat
6                -2 from /data/shuklax/xyz_channel/xyz_channel_110.dat
6               -12 from /data/shuklax/xyz_channel/xyz_channel_111.dat
6                -9 from /data/shuklax/xyz_channel/xyz_channel_112.dat
6                 1 from /data/shuklax/xyz_channel/xyz_channel_113.dat
6                -8 from /data/shuklax/xyz_channel/xyz_channel_114.dat
6                 1 from /data/shuklax/xyz_channel/xyz_channel_115.dat
6                -5 from /data/shuklax/xyz_channel/xyz_channel_116.dat
6               -16 from /data/shuklax/xyz_channel/xyz_channel_117.dat
6                -2 from /data/shuklax/xyz_channel/xyz_channel_118.dat
6                -3 from /data/shuklax/xyz_channel/xyz_channel_119.dat
6                -1 from /data/shuklax/xyz_channel/xyz_channel_12.dat
6               -13 from /data/shuklax/xyz_channel/xyz_channel_120.dat
6                10 from /data/shuklax/xyz_channel/xyz_channel_121.dat
6               -15 from /data/shuklax/xyz_channel/xyz_channel_122.dat
6                 0 from /data/shuklax/xyz_channel/xyz_channel_123.dat
6               -11 from /data/shuklax/xyz_channel/xyz_channel_124.dat

I want the output from the files …

d5e5 109 Master Poster

Hi,
@mitchems & @d5e5 ........Thank you very much.
@d5e5......... in my case; it matters that 'diff' should be done in numerical order i.e. start from file xyz_channel_1.dat,.... and should finish with xyz_channel_200.dat.

so, as far as i understand this 'glob' will then not work...

with help from both of you; i have made the code below; but it is not printing anything.... i want to save the output in a file called out.dat.

in fact in out.dat file i want to print two coloms; 1st colom will be some corresponding values;

my $velocity;
for ($velocity=3; $velocity=203; $velocity=$velocity+1)

and second colom will be 'diff' from files, which starts from xyz_channel_1.dat...
so out.dat will look like following

3             'diff'from xyz_channel_1.dat 
4             'diff'from xyz_channel_2.dat 
5             'diff'from xyz_channel_3.dat
6             'diff'from xyz_channel_4.dat
.
.
.
.
.
203            'diff'from xyz_channel_200.dat
#!/usr/bin/perl
use strict;
use warnings;

my $velocity;
for ($velocity=3; $velocity=203; $velocity=$velocity+1); 
 
my ($start_range1, $end_range1, $start_range2, $end_range2) = (20, 30, 100, 110);
opendir(DATA, "/shuklax/data/xyz_channel") || die "Can't open data directory \n";

# all the files xyz_chennel_1.dat ...... xyz_chennel_200.dat are in "/shuklax/data/xyz_channel".....

while( $file = readdir(DATA) )
{
foreach my $f ($file){
    my ($sum1, $sum2) = integrate_file($f);
    my $diff = $sum2 - $sum1;
    print "$f $sum1 $sum2 $diff\n";
}
 
sub integrate_file {
    my $file = $_[0];
    my ($s1, $s2) = (0, 0);
    open my $fin, '<', $file or die "Failed to open $file: $!";
    $_ = <$fin>; #Skip first line
    while (<$fin>){
        my ($x, $y) = split(/ /, $_);
        $s1 += $y if ($x >= …
d5e5 109 Master Poster

Well, one important difference between my solution and yours is that I am making full use of references and you're not. I'm not saying that's better or worse, but for a newbie, perhaps he doesn't understand references that well and if he's doing it for a class, the teacher will probably not believe that he wrote either of our solutions :-), especially mine because of all the de-referencing stuff.

BTW, I like the "glob" way of reading the files. I typically use something like this:

opendir(DATA, "$DATAROOT/$dir") || die "Can't open data directory ($DATAROOT)\n";
while( $file = readdir(DATA) )
{
 #do something with each file
}

But both work! Nice job! I love how perl allows you to you stuff so many different ways.

Yes, references can be very useful but the notation looks scary when you're new to Perl. When reading files into an array I used to avoid using references too as I found the various alternative notations confusing. Instead I would save each line as an array element and split the element into another array as needed to access the component fields (which could require splitting the same array element more than once). But sometimes references are pretty much essential, such as for passing or returning more than one list to or from subroutines -- so it's good to become familiar with them sooner or later. (Not to mention hash references. Passing attributes to objects and saving complex data to databases require hashes and hash references.)

As …

d5e5 109 Master Poster

OK, try this. Not saying it's better than mitchems' solution, just different.

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

my ($start_range1, $end_range1, $start_range2, $end_range2) = (2, 4, 2, 5);
my $cur_dir = "/home/david/Programming/Perl"; #Path to data files on my computer
my @files_to_integrate = glob("$cur_dir/xyz_channel_*.dat");

foreach my $f (@files_to_integrate){
    my ($sum1, $sum2) = integrate_file($f);
    my $diff = $sum2 - $sum1;
    print "$f $sum1 $sum2 $diff\n";
}

sub integrate_file {
    my $file = $_[0];
    my ($s1, $s2) = (0, 0);
    open my $fin, '<', $file or die "Failed to open $file: $!";
    $_ = <$fin>; #Skip first line
    while (<$fin>){
        my ($x, $y) = split(/ /, $_);
        $s1 += $y if ($x >= $start_range1) and ($x <= $end_range1);
        $s2 += $y if ($x >= $start_range2) and ($x <= $end_range2);
    }
    return ($s1, $s2)
}
d5e5 109 Master Poster

My wife says I have to turn off the computer now so this is just a stub. The following shows you can use glob to do something to every file that is named according to a specific pattern:

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

my @files_to_integrate = glob("/home/david/Programming/Perl/xyz_channel_*.dat");

foreach my $f (@files_to_integrate){
    integrate_file($f);
}

sub integrate_file {
    my $file = $_[0];
    print "Integrating $file now\n";
}

I think you said you want to do two integrations and calculate the difference on each file, correct? I hope to have time to look at this a little more tomorrow.

d5e5 109 Master Poster

I made up a simplified data file containing the following:

Tom,no,2009
Dick,no,2008
Harry,se,2010
Jane,ip,2009
Frank,te,2007

Notice the last record has a deliberately invalid item for testing. The following should print your data, after looking up the desired values for $dat_type that are defined in a hash. Using a hash means you don't need a complex if-else statement to test every possible $dat_type.

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

# %dtypes hash will associate dat_type keys with values to print
my %dtypes = (no => 'nokia',
              se => 'sony ericsson',
              ip => 'iphone');

my $dat_file = 'sample.csv';

open (F, $dat_file) or die ("Could not open $dat_file: $!");

my $type2print;
printf "%-10s%-25s%-10s\n", ('Name', 'Type', 'Year');
while (my $line = <F>){
    chomp $line; #Remove trailing linefeed
    my ($name,$dat_type,$year) = split ',', $line;
    
    if (exists $dtypes{$dat_type}) {
        $type2print = $dtypes{$dat_type}
    }else{
        $type2print = "Unknown Type '$dat_type'";
    }

    printf "%-10s%-25s%-10s\n", ($name, $type2print, $year);
}

This prints the following output:

Name      Type                     Year      
Tom       nokia                    2009      
Dick      nokia                    2008      
Harry     sony ericsson            2010      
Jane      iphone                   2009      
Frank     Unknown Type 'te'        2007
d5e5 109 Master Poster

Sorry, tonyjv, I posted the above before noticing your solution, and it was too late to edit or delete mine. I agree it is much better to call the same function for each weekday than to define separate functions for Monday, Tuesday, etc.

d5e5 109 Master Poster

The ValueError occurs after your while valid == False: loop has completed. Since the ValueError occurs outside the loop where you do your exception handling, it is not handled and so crashes the program.

d5e5 109 Master Poster

Thanks tonyjv, but I just can't figure this out. Using my incredible genius, (sarcasm) it finally clicked in my brain that the code in red cannot possibly give me how many minutes are left along with the hours. Because the code there now is meant to show me how many minutes are in the number of hours they worked! :$

It's supposed to show how many hours they worked, and then how many minutes are left.
Like, if the clock in time is 11:20AM, and clock out time is 9:15PM. The program should say that they worked 9 hours and 55 minutes that day.

import time

print "When did they clock in? Use HH:MMtt format."
clockIn = raw_input()

timeString1 = "05/23/10 " + clockIn
timeTuple1 = time.strptime(timeString1, "%m/%d/%y %I:%M%p")

print "When did they clock out?"
clockOut = raw_input()

timeString2 = "05/23/10 " + clockOut
timeTuple2 = time.strptime(timeString2, "%m/%d/%y %I:%M%p")

totalTime = time.mktime(timeTuple2) - time.mktime(timeTuple1)

print "They worked",totalTime//(60.0*60),"hours and",totalTime/60.0,"minutes today."

Here is what happens when I enter the clock in and clock out time I said above.

IDLE 2.6.5 ==== No Subprocess ====
>>>
When did they clock in? Use HH:MMtt format.
11:20AM
When did they clock out?
9:15PM
They worked 9.0 hours and 595.0 minutes today.
>>>

I don't know where to go from here to make this work...

Your code neglects to subtract the minutes that you have already converted into hours from the remaining minutes. For example, to convert 65 minutes …

d5e5 109 Master Poster

Let me see if I got this right:

os.startfile("PATH OR URL") would open the defaultbrowser for windows and send it there?

and

webbrowser.open("PATH OR URL") would do the same but for any platform?


can you clarify why they are so different?? Which one is better???

When the os module is compiled on an non-Windows platform it doesn't have a startfile attribute or method. I guess os.startfile works on Windows by checking the Windows registry for associations between the file extension and its default program.

webbrowser.open("PATH OR URL") works on both Windows and Linux, etc., presumably because it does not depend on the Windows registry to discover the default browser. That's all I know about os.startfile and webbrowser.open so far so can't say which is best.

d5e5 109 Master Poster
>>> import webbrowser
>>> webbrowser.open('/home/david/index.html')
True
>>>

It opens my default browser, Firefox, and displays my index.html file. I think it's supposed to do the same on other platforms.

d5e5 109 Master Poster

Look at vegaseat's code snippet about date and time handling and scroll down to the part that says "Calculate difference between two times (12 hour format) of a day:". That looks like what you need.

d5e5 109 Master Poster

I made up the following data to test and put it in a file called 'users.csv'.

"Name","ComplicatedColumn","AccountDisabled","OnSite",
"Fred","Age=25,Pet=Fish","0","1",
"Donna","Age=29,Pet=Cat","0","1",
"Tom","Age=35,Pet=Gerbil","1","0",
"Linda","Age=27,Pet=Dog","0","0",

The following works for me (finally) except if the "AccountDisabled" header name doesn't exist in the file it won't catch that error... so it may need better error-checking.

#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
my $dir = '/home/david/Programming/Perl';
my $file = $dir . '/' . 'users.csv';

my $csv = Text::CSV->new({always_quote => 1});


open (my $fh, "<", $file) or die $!;
my @file = <$fh>;
close $fh;
my $check_colname= "AccountDisabled";
my $check_col_index;
if ($csv->parse($file[0])) { #Look at the first line to find index of column name
    my @header = $csv->fields();
    ($check_col_index) = grep { $header[$_] eq $check_colname} 0..$#header;
    print "Index is $check_col_index\n";
}else{
    die "Couldn't parse first line of $file";
}

foreach (@file) { #Loop through array and print
    if ($csv->parse($_)) {
        my @columns = $csv->fields();
        next if $columns[$check_col_index] eq "1"; #If AccountDisabled column has a "1" in it
        my $status = $csv->combine(@columns);    # combine columns into a string
        my $line   = $csv->string();             # get the combined string
        print "$line\n";
    } else {
        my $err = $csv->error_input;
        print "Failed to parse line: $err";
    }
}

I'll be away tomorrow (Saturday). Have a good weekend.

BastienP commented: Once again something 100% usefull. Bastien +1
mitchems commented: Nice use of Text::CSV! +2
d5e5 109 Master Poster

Hello d5e5

I've already tried that but with no success... And the mentionned script is working when Distinguishedname is encountered in the whole column so I thought it would be pretty easy to adapt it, but I think I was mistaking, 'cause I'm not finding out how to do that !

Any idea ?

If you've gotta working script with a parsing module I'd be glad to try it though ! :o)

Thanks by advance,
Bastien

#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
my $dir = '/home/david/Programming/Perl';
my $file = $dir . '/' . 'input-light.csv';

my $csv = Text::CSV->new();

open (my $fh, "<", $file) or die $!;
my @file = <$fh>;
close $fh;

my $str2find = "Distinguishedname";
my $dropcol;
foreach (@file) { #Loop through array 1st time to find index of column to drop
    if ($csv->parse($_)) {
        my @columns = $csv->fields();
        my $rv = idx (\@columns, $str2find);
        $dropcol = $rv if defined($rv);
    } else {
        my $err = $csv->error_input;
        print "Failed to parse line: $err";
    }
}

foreach (@file) { #Loop through array 2nd time to print data without dropped column
    if ($csv->parse($_)) {
        my @columns = $csv->fields();
        splice (@columns, $dropcol, 1); #Remove column starting at $dropcol for length of 1
        my $status = $csv->combine(@columns);    # combine columns into a string
        my $line   = $csv->string();             # get the combined string
        print "$line\n";
    } else {
        my $err = $csv->error_input;
        print "Failed to parse line: $err";
    }
}

sub idx {#Loop through array, return index of string if found …
BastienP commented: Great response that solved my problem ! +1
d5e5 109 Master Poster

I haven't figured this out yet but I think the first step for something with somewhat complex CSV parsing requirements would be to choose and install a good CSV parsing module for Perl. There are some simple examples of Parsing CSV at this link.

d5e5 109 Master Poster

The brute force approach is maybe not so bad since you don't have to lower the entire dictionary, just the string of its keys.

>>> d = {'Spam': 2, 'Ham': 1, 'Eggs': 3} #Here is a dictionary
>>> s = str(d.keys()) #Here is a string of its keys
>>> 'ham' in s.lower()
True
>>>
d5e5 109 Master Poster

Here's my 2 cents on what (not year%4 and year%100 or not year%400) and True is doing. Python knows it is evaluating a Boolean expression and so it evaluates as much as it needs to, evaluating each component expression according to the rules of precedence, until it get a definite answer to whether the whole expression is true or false. But what it returns seems to be the last component expression evaluated. Accordingly,

>>> 'Boy' and 'Girl'
      'Girl'
>>>

returns 'Girl', not because a girl is more useful than a boy, but because 'Girl' was the last component that needed to be evaluated to determine the value of the whole expression. But that's not all. If instead of 'Girl' we had 3 > 2 the result would be True. Apparently expressions such as 'Girl', 7, etc. will evaluate to True in a Boolean context but otherwise their values are not automatically converted to True or False. But other expressions such as "Fred" > "Barney" are automatically evaluated as Boolean.

>>> 0 and "Genius"
0
>>> 3 < 2 and "Genius"
False
>>>
d5e5 109 Master Poster

I'm not comfortable with setting up key index columns but I may be able to answer some questions about a hash. With what about the concept of hash are you not comfortable?

The main things you need to know, in order to read a file into a hash are

  • How to declare a hash
  • How to add a key-value pair to a hash and that only scalar keys and values can be stored in a hash
  • How to check if a particular key exists in your hash, and if it does, how to access it
  • How to iterate through your keys so you can access all the key-value pairs

Given a file named b.txt which contains the following:

abcd,abrd,fun,D000,$12,$234,$212,$200,$200,$200
dear,dare,tun,D000,$12.00405,$234.08976,$212.09876,$200,$200,$200

here is an example of how you can read this file into a hash and then iterate through and print the keys and values:

#!/usr/bin/perl -w
use strict;
use warnings;
my $filename_b = '/home/david/Programming/Perl/b.txt';
my %b = %{read_into_hash($filename_b)};

foreach (keys %b) {
    print "The key $_ has $b{$_} as its value\n";
    my $aref = $b{$_};
    print "$b{$_} is a reference to an array containing @{$aref}\n";
}

sub read_into_hash {
    my $file = $_[0];
    my %h = ();
    open (my $fh, '<', $file);
    while (<$fh>) {
        my @fields = split(/,/);
        my $hkey = join(",", @fields[0..3]);
        $h{$hkey} = [@fields[4..9]];
    }
    return \%h;
}
d5e5 109 Master Poster

Could you attach a copy of data_file_1.dat to your post? Or if you could post some of the data (within code tags) it would make it easier to help you with this.

d5e5 109 Master Poster

Try adding the following to the validate function.

var ccnum = document.getElementById("credit card number").value;
        var alldig = false;
        alldig = /^\s*\d+\s*$/.test(ccnum); //Consecutive digits, optional leading or trailing spaces        
	if (alldig == false)
	{
		alert("Credit Card Number must consist of numbers only");
		return false;
	}
d5e5 109 Master Poster

os.popen returns an object that you can assign to a variable and iterate through. I read about it at http://linux.byexamples.com/archives/366/python-how-to-run-a-command-line-within-python/

>>> import os
>>> f=os.popen("ls -la")
>>> for i in f.readlines():
	print "myresult:", i,

	
myresult: total 9804
myresult: drwxr-xr-x 55 david david    4096 2010-05-04 16:28 .
myresult: drwxr-xr-x  3 root  root     4096 2010-02-25 16:05 ..
myresult: drwx------  3 david david    4096 2010-02-26 14:37 .adobe
myresult: -rw-------  1 david david    9596 2010-05-03 11:38 .bash_history
etc......................