d5e5 109 Master Poster

Hi,

Thanks for your reply i m really thank full for such a fast reply,but i have a problem the code from the post reply shows some error can't open

Is it that if the folder name in the path that we mention should not contain spaces..?

That's probably it. Try adding use File::Glob qw(bsd_glob); to the program.

d5e5 109 Master Poster

Hi,


This is my first post in the forum.
I got a situation where i have to find a file in a folder based on its extension and there by use the file name and contents of the file.

Thanks for the reply.

If the extension of the files you want to use is ".txt", for example, you could do the following:

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

my $folder = '/home/david/Programming/data';
foreach(glob "$folder/*.txt"){
    use_contents($_);
}

sub use_contents{
    my $filename = shift;
    print "$filename\n", '-' x 75, "\n";
    open my $fh, '<', $filename or die "Can't open $filename: $!";
    foreach(<$fh>){
        print;
    }
    print "\n", '-' x 75, "\n\n";
}
d5e5 109 Master Poster

I should have put more error-checking to test if it successfully opened the files. Here is an improved version. Make sure the files 1.txt and 2.txt (attached to this post) exist in your current working directory so the script can open them.

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

my %hash;
my $file1 = '1.txt';
my $file2 = '2.txt';

open my $fh, '<', $file2 or die "Can't open $file2: $!";
while (<$fh>){
    chomp;
    my @flds = split;
    my $fullname = $flds[0];
    my $name = fileparse($fullname,qw(.fit .vcor)); #Remove the file extension
    $hash{$name} = join ' ', @flds[2..$#flds];
}
close $fh;

open $fh, '<', $file1 or die "Can't open $file1: $!";
while (<$fh>){
    chomp;
    my @flds = split;
    my $fullname = $flds[0];
    my $name = fileparse($fullname,qw(.fit .vcor)); #Remove the file extension
    if (exists $hash{$name}){
        print "$name @flds[2..$#flds] $name $hash{$name}\n";
    }
    else{
        print "$name @flds[2..$#flds] in list1 matches nothing in list2\n";
    }
}
d5e5 109 Master Poster
#!/usr/bin/perl
use strict;
use warnings;
use File::Basename;

my %hash;

open my $fh, '<', '2.txt';
while (<$fh>){
    chomp;
    my @flds = split;
    my $fullname = $flds[0];
    my $name = fileparse($fullname,qw(.fit .vcor)); #Remove the file extension
    $hash{$name} = join ' ', @flds[2..$#flds];
}
close $fh;

open $fh, '<', '1.txt';
while (<$fh>){
    chomp;
    my @flds = split;
    my $fullname = $flds[0];
    my $name = fileparse($fullname,qw(.fit .vcor)); #Remove the file extension
    if (exists $hash{$name}){
        print "$name @flds[2..$#flds] $name $hash{$name}\n";
    }
    else{
        print "$name @flds[2..$#flds] in list1 matches nothing in list2\n";
    }
}

Gives the following output:

1aw7_AB 1 2 3 1aw7_AB 4 5 6
1bjw_AB 9 4 7 1bjw_AB 2 7 7
1biq_AB 8 0 1 in list1 matches nothing in list2
d5e5 109 Master Poster

After posting the above I tried substituting 'l' for 'N' in your original script and it also printed -1 for me, so I guess the problem is you are running it on a different platform. I'm using Ubuntu 10.04.3 LTS and my computer is 32-bit.

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

print bin2dec('1' x 32); #Prints -1

sub bin2dec { 
	return unpack("l", pack("B32", substr("0" x 32 . shift, -32))); 
}
d5e5 109 Master Poster

yeah, I'm using two's compliment
0xFFFFFFFF (stored in binary bitstring)
should be -1, but it is showing up as 4294967295

You said you already tried the 'l' template and it gave you something wrong. On my computer it seems to work OK. Did you test it in something like the following way?

0xFFFFFFFF (stored in binary bitstring) would be a string of 32 1's, right?

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

my $bitstring = '1' x 32; #String of 32 1's

my $pl = pack 'l', $bitstring; #Create a packed long integer

my ($num) = unpack 'l', $pl;

print $num; #Prints -1
d5e5 109 Master Poster

Please show us an example of a negative bitstring. I think that since you say "big-endian" you have generated your bitstring according to the 2's Complement method but I'm not sure about that.

There are two methods for storing negative binary numbers, they are Sign and Magnitude and 2's Complement.

d5e5 109 Master Poster

If you want to save the results of a query in a table have a look at create table select.

d5e5 109 Master Poster
#!/usr/bin/perl
use strict;
use warnings;

my (@array, $foundvar1, $foundvar2);

while (<DATA>){
    chomp;
    if (m/Var1 data:/){
        $foundvar1 = 1;
    }
    elsif (m/Var2 data:/){
        $foundvar1 = 0;
        $foundvar2 = 1;
    }
    else {
        if ($foundvar1){
            my @rec = split /,/, $_;
            push @{$array[0]}, join ',', @rec;
        }
        if ($foundvar2){
            my @rec = split /,/, $_;
            push @{$array[1]}, join ',', @rec[0..2];
        }
    }
}

foreach(0 ..  $#{$array[0]}){
    print "${$array[0]}[$_], ${$array[1]}[$_]\n";
}
__DATA__
Var1 data:
455,0,0,0,0
135,0,0,0,0
199,0,0,0,0
Var2 data:
131.253.4.131,1,0,,
131.253.7.54,1,0,,
10.80.5.3,1,0,,

Outputs the following:

455,0,0,0,0, 131.253.4.131,1,0
135,0,0,0,0, 131.253.7.54,1,0
199,0,0,0,0, 10.80.5.3,1,0
d5e5 109 Master Poster

one more thing..I am newbie in perl so trying to learn..does return 1 always denotes true and return 0 always returns false..and is it mandatory to use them in subroutines? Also many perl books says that while can be used for multi line file looping. But in my case it did not work. Then can we say, while loop is not useful always?
thanks

My subroutine returns 1 or 0 because I want to evaluate the subroutine in a boolean context. In the above script if ( already_in_file($input) ){... calls the subroutine and evaluates it in a boolean context in which undef, zero, empty string and empty list evaluate to false and anything else evaluates to true.
Truth and Falsehood...The number 0, the strings '0' and '' , the empty list () , and undef are all false in a boolean context. All other values are true. Negation of a true value by ! or not returns a special false value. When evaluated as a string it is treated as '' , but as a number, it is treated as 0.

It is not mandatory for a subroutine to return 1 or 0. You could have a subroutine return any value you want.

Sure you can use a while loop to loop through a multi-line file, but in the above script you wanted to loop through and sometimes add to the file, so using Tie::File lets you treat the file like an array. I find …

d5e5 109 Master Poster

The Tie::File module lets you treat a file like an array so you can repeatedly loop through it and push new records into it.

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

use Tie::File;

my $filename = '/home/david/Programming/data/new1.txt';

tie my @array, 'Tie::File', $filename or die "Unable to Tie $filename: $!";

my ($input, $input1);

($input, $input1) = ('David', 'at home');#Try adding myself

if ( already_in_file($input) ){
    print "User name already exists.\n";
}
else{
    push @array, "$input\t$input1";
    print "Added $input to $filename.\n"
}

sub already_in_file{
    my $u2find = shift;
    my $user;
    
    foreach (@array){
        ($user) = split /\t/;
        if ($user =~ m/$u2find/i){
            return 1;#True if user already in file
        }
    }
    return 0;#False if user not found in file
}
d5e5 109 Master Poster

Thanks, it worked.

You're welcome. Please don't forget to mark this thread 'solved'.

d5e5 109 Master Poster

I don't have your kind of database and am not familiar with awk so I don't understand your script. To create an output file whose name is the current date you can do the following:

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

my ($day, $month, $year) = (localtime)[3,4,5];
my $filename = sprintf("%04d-%02d-%02d\n", $year+1900, $month+1, $day);

open my $fh, '>', $filename;

print $fh "This file should have today's date as it's name.";
d5e5 109 Master Poster

Thanks a lot!! It works..I think my mistake was in the command as I missed 'Local' and 'Lines terminated' parts.
I have one more question. Searched Google for it but no help. I think I am searching wrong terms.
I have attached another small tab delimited text file attached here. I want the corresponding rows should come. For eg. If I select Country="England", then I want the output with all the corresponding cities and Particiapnats.
So the output table should look like:

Country  Cities Participants
England     Taunton   225
            Bristol   654
            Plymouth  585
England     London    552
            Exeter    235
            Leeds     445

I tried using LIMIT but no luck (or I am not using it correctly!) (Please note that the numbers showing here is not part of my table!)
Please suugest..
Thanks

Your input table has no country associated with most of the cities, such as Bristol, Plymouth, Exeter and Leeds. When you write a SELECT query you can easily retrieve the rows that contain 'England', but of course that will miss the rows where country is null. I don't know of any way around that except to manually fill in all null values in the country column with the appropriate country. You know that Leeds is in England, but MySQL does not.

d5e5 109 Master Poster

If you have generated the text file on a Windows system, you might have to use LINES TERMINATED BY '\r\n' to read the file properly, because Windows programs typically use two characters as a line terminator. Some programs, such as WordPad, might use \r as a line terminator when writing files. To read such files, use LINES TERMINATED BY '\r'.

see note in docs for LOAD DATA
The following works on my linux computer. (I don't have MySQL on Windows.)

DROP TABLE IF EXISTS `all_text`;
CREATE TABLE `all_text`(
`country` VARCHAR(20),
`some_nbr` VARCHAR(20),
`city` VARCHAR(20),
`gender` VARCHAR(20),
`vote` VARCHAR(20)
) ENGINE = MYISAM;

#Change the file path to get this to run on your computer
LOAD DATA LOCAL INFILE "/home/david/Programming/data/test.txt" INTO TABLE all_text
LINES TERMINATED BY '\r\n';

SELECT * FROM all_text;

The result of the above is

+-----------+----------+------+--------+----------+
| country   | some_nbr | city | gender | vote     |
+-----------+----------+------+--------+----------+
| Australia | Sydney   | 55   | M      | 245254   |
|           | Beijing  | 65   | M      | 22254    |
| Greece    | Athens   |      | F      | 2222AVG5 |
| Thailand  | Bangkok  | 42   | M      | 76577    |
| Malayasia |          | 22   | M      | 7676578  |
| Japan     | Tokyo    | 75   | F      | 987765   |
| Chile     | Santiago | 58   | F      | 5453ASD  |
| Russia    | Moscow   | 75   | F      | 343545   |
| Uganada   |          |      | M      | 676867   |
| Canada    | Montreal | 77   | M      | 4544345  |
+-----------+----------+------+--------+----------+
debasisdas commented: agree +13
d5e5 109 Master Poster

Hi Thanks for your reply. I tried making a test table to populate with my data where some data are missing as well like before. But now the problem is different which you could see from this image. The first Country column VARCHAR(20) is not coming properly! Country names are like Australia, Greece etc..
[IMG]http://i56.tinypic.com/2cnfri9.jpg[/IMG]
But missing data in columns City, Age are loading properly now..
Please note that, I am doing all these in my Windows computer. I saved the data first in .xlsx format and then saved them as tab delimited text.
Command used to load data:
LOAD DATA INFILE "J/MySQL/test.txt" INTO TABLE test;
Thanks..

If you attach your test.txt tab delimited file to your post we could test the import and try to replicate the error.

d5e5 109 Master Poster

Try creating a table having the same column names whose columns are all VARCHAR and import your data into that. That should work as long as your VARCHAR columns are big enough. Then you can write a query that reads the data from this all-VARCHAR table and INSERTs into the table you want to populate. That seems like a roundabout way to do it, but I used to do that a lot years ago when I had problems importing a file. If you have to convert a value from VARCHAR to INT, it's easier to handle that in your insert query that selects from your intermediate table.

d5e5 109 Master Poster

I think the map name must correspond to what you refer to in usemap. In your example, usemap="#bearface" but <map name="bear">

d5e5 109 Master Poster

Current Turn Around Time does not belong in your table. Make it a calculated column in the query that selects from your table. The following shows an item that came in 12 days ago and hasn't gone out yet so date_out is NULL.

CREATE TABLE IF NOT EXISTS `test`(
`id` INT NOT NULL AUTO_INCREMENT ,
`date_in` DATETIME NOT NULL ,
`date_out` DATETIME,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM;

INSERT INTO `daniweb`.`test` (
`id` ,
`date_in` ,
`date_out`
)
VALUES (
1 , '2011-07-01 15:29:50', NULL
);

SELECT date_in, DATEDIFF(IF(date_out IS NULL, NOW(), date_out), date_in) as turnaround, date_out
FROM `test`;
d5e5 109 Master Poster

Thank you David! This is working perfectly fine for me.Thanks again!

You are welcome. Please don't forget to mark this thread 'solved'.

d5e5 109 Master Poster

Instead of the above solution, you could simply write a function to return the portion of the record that you want to compare.

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

my ($file1, $file2, $file3) = qw(1.txt 2.txt 3.txt);
open my $fh1, '<', $file1 or die "Can't open $file1: $!";
open my $fh2, '<', $file2 or die "Can't open $file2: $!";
open my $fh3, '>', $file3 or die "Can't open $file3: $!";

my %save; #Hash of hashes to store records from file1 for comparison with file2
while (<$fh1>){
    chomp;
    my @rec = split /\|/;
    my $key = $rec[2];
    $save{$key}->{'data'} = $_; #Save current record in hash
    $save{$key}->{'flag'} = 'D';
}

while (<$fh2>){
    chomp;
    my @rec = split /\|/;
    my $key = $rec[2];
    
    if (not exists $save{$key}){
        $save{$key}->{'data'} = $_;
        $save{$key}->{'flag'} = 'I';
    }elsif (string_to_compare($_) ne string_to_compare($save{$key}->{'data'})){
        $save{$key}->{'data'} = $_;
        $save{$key}->{'flag'} = 'U';
    }else{
        delete $save{$key};
    }
}

foreach (sort keys %save){
    print $fh3 "$save{$_}->{'data'}|$save{$_}->{'flag'}\n";
}

sub string_to_compare{
    my $line = shift;
    my ($skip1, $skip2, $key, $remainder) = split /\|/, $line, 4;
    return $remainder;
}
Salem commented: For effort, even though the OP is getting a free ride +17
k_manimuthu commented: Nice coding sequence & derivation +5
d5e5 109 Master Poster

Thanks David! This is working for me.

Also, I have realised one thing for flag 'U' that for find update flag - I don't need to consider first & second column. Since first & second columns are like timestamp & ID. So, for 'U' - comparision should start from third column (unique column).

So, I thinking to remove first two column at very initial step & before starting this comparision from both input files. Could please suggest any other approach here?

In that case I would save the portion following the unique column in a separate element of the %save data called 'compare_this' and use it for comparing with the corresponding remainder of each record from file2.

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

my ($file1, $file2, $file3) = qw(1.txt 2.txt 3.txt);
open my $fh1, '<', $file1 or die "Can't open $file1: $!";
open my $fh2, '<', $file2 or die "Can't open $file2: $!";
open my $fh3, '>', $file3 or die "Can't open $file3: $!";

my %save; #Hash of hashes to store records from file1 for comparison with file2
while (<$fh1>){
    chomp;
    my ($skip1, $skip2, $key, $remainder) = split(/\|/, $_, 4);
    $save{$key}->{'data'} = $_; #Save current record in hash
    $save{$key}->{'compare_this'} = $remainder; #Save last part of current record in hash
    $save{$key}->{'flag'} = 'D';
}

while (<$fh2>){
    chomp;
    my @rec = split /\|/;
    my ($skip1, $skip2, $key, $remainder) = split(/\|/, $_, 4);
    
    if (not exists $save{$key}){
        $save{$key}->{'data'} = $_;
        $save{$key}->{'flag'} = 'I';
    }elsif ($remainder ne $save{$key}->{'compare_this'}){
        $save{$key}->{'data'} = $_;
        $save{$key}->{'flag'} = 'U'; …
d5e5 109 Master Poster

For this data I would suggest reading and saving the first file into a hash of hashes to save each record with a flag with value of 'D'. Then read through the second file to compare its records with the saved records and change the flag's value as needed.

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

my ($file1, $file2, $file3) = qw(1.txt 2.txt 3.txt);
open my $fh1, '<', $file1 or die "Can't open $file1: $!";
open my $fh2, '<', $file2 or die "Can't open $file2: $!";
open my $fh3, '>', $file3 or die "Can't open $file3: $!";

my %save; #Hash of hashes to store records from file1 for comparison with file2
while (<$fh1>){
    chomp;
    my @rec = split /\|/;
    my $key = $rec[2];
    $save{$key}->{'data'} = $_; #Save current record in hash
    $save{$key}->{'flag'} = 'D';
}

while (<$fh2>){
    chomp;
    my @rec = split /\|/;
    my $key = $rec[2];
    
    if (not exists $save{$key}){
        $save{$key}->{'data'} = $_;
        $save{$key}->{'flag'} = 'I';
    }elsif ($_ ne $save{$key}->{'data'}){
        $save{$key}->{'data'} = $_;
        $save{$key}->{'flag'} = 'U';
    }else{
        delete $save{$key};
    }
}

foreach (sort keys %save){
    print $fh3 "$save{$_}->{'data'}|$save{$_}->{'flag'}\n";
}
d5e5 109 Master Poster
#!/usr/bin/perl
use strict;
use warnings;

my ($file1, $file2, $file3) = qw(1.txt 2.txt 3.txt);
open my $fh1, '<', $file1 or die "Can't open $file1: $!";
open my $fh2, '<', $file2 or die "Can't open $file2: $!";
open my $fh3, '>', $file3 or die "Can't open $file3: $!";

while (<$fh1>){
    last if eof($fh2);
    my $comp_line = <$fh2>;
    chomp($_, $comp_line);
    my @rec1 = split /\|/;
    my @rec2 = split /\|/, $comp_line;
    
    #I-Insert, D-Delete, U-Update
    print $fh3 "$rec2[0]|$rec2[1]|U\n" if $rec2[0] eq $rec1[0] and $rec2[1] ne $rec1[1];
    print $fh3 "$rec1[0]|$rec1[1]|D\n" if $rec2[0] ne $rec1[0] and $rec2[1] ne $rec1[1];
    print $fh3 "$rec2[0]|$rec2[1]|I\n" if $rec2[0] ne $rec1[0];
}
d5e5 109 Master Poster

The previous script uses the parse_file() method to automatically open and parse the entire file. If you want to parse a file that is already open (such as STDIN) or you want to parse only some records in a large file then you can use the parse() method instead. (I can't find it in the source Parser.pm file either but that doesn't seem to matter -- it works for me anyway.) The following script loops through a file already open in STDIN, and parses it and prints some output.

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

use HTML::Parser ();

# Create parser object
my $p = HTML::Parser->new( api_version => 3,
                        start_h => [\&start, "tagname, text"],
                        text_h  => [\&text,  "text"],
                        end_h   => [\&end,   "tagname, text"],
                        marked_sections => 1,
                      );

# Loop through STDIN and parse each line.
while (<>){
    $p->parse($_);
}
print "\n";

$p->eof;#Tell Parser object we're finished parsing this file

sub start{
    my ($tagname, $text) = @_;
    print "<!-- $tagname starts here................-->\n";
    print $text;
}

sub text{
    my $text = shift;
    print $text;
}

sub end{
    my ($tagname, $text) = @_;
    print "\n<!-- $tagname ends here................-->\n";
    print $text;
}
d5e5 109 Master Poster

Undefined subroutine &main::start called at getwords.pl line 27.

The error message says it can't find your start function. It doesn't mention a function named 'parse', you need to define a function or subroutine named 'start' in your main package.

For example, if you have an html file in your current working directory name 'VerySimpleFile.html' the following script should run OK:

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

use HTML::Parser ();

# Create parser object
my $p = HTML::Parser->new( api_version => 3,
                        start_h => [\&start, "tagname, text"],
                        text_h  => [\&text,  "text"],
                        end_h   => [\&end,   "tagname, text"],
                        marked_sections => 1,
                      );

# Parse directly from file

$p->parse_file('VerySimpleFile.html');

sub start{
    my ($tagname, $text) = @_;
    print "<!-- $tagname starts here................-->\n";
    print $text;
}

sub text{
    my $text = shift;
    print $text;
}

sub end{
    my ($tagname, $text) = @_;
    print "\n<!-- $tagname ends here................-->\n";
    print $text;
}
d5e5 109 Master Poster

If you don't test whether each of your open statements succeeded by adding or die $! you won't know which one of them fails. See the simple examples at the beginning of perldoc -f open. Also every script should use strict; use warnings;

d5e5 109 Master Poster

How about converting the 32-bit hex string to a string of ones and zeros representing the value converted to binary? Then you can keep the first n number of bits and concatenate with the possible ending strings of bits to get one or more 32-bit binary strings which you can convert to hex strings.

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

my @examples = ('255.102.25.02/32',
                '255.102.25.02/31',
                '131.166.254.0/29');
my @results;

foreach my $example(@examples){
    my ($ip, $bits) = split /\//, $example;
    push @results, ip2hex($ip, $bits);
}

my $i = 0;
foreach(@examples){
    my $string = join(', ', @{$results[$i++]});
    print "$_ ==> $string\n";
}

sub convert32{
    my $ip = shift;
    my @octets = split /\./, $ip;
    my $result;
    my @arr;
    foreach (@octets){
        $result .= sprintf("%02X", $_);
    }
    return $result;
}

sub ip2hex{
    my ($ip, $n) = @_;
    my @arrbin;
    my @arrhex;
    #The nearest 32-bit string
    my $str32 = convert32($ip);
    if ($n == 32){
        return [$str32];
    }
    my $onesandzeros = dec2bin(hex($str32));
    my $keepbits = substr($onesandzeros, 0, $n);
    my @varybits;
    my $len = 32 - $n;
    my $start = '0' x ($len);
    my $end = '1' x ($len);
    push @varybits, sprintf("%0${len}s", dec2bin($_)) foreach (bin2dec($start) .. bin2dec($end));
    push @arrbin, $keepbits . $_ foreach (@varybits);
    push @arrhex, convert32(bin2dec($_)) foreach (@arrbin);
    return \@arrhex;#Reference to array;
}

sub dec2bin {
    #see http://docstore.mik.ua/orelly/perl/cookbook/ch02_05.htm
    my $str = unpack("B32", pack("N", shift));
    $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros
    return $str;
}

sub bin2dec {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}

This gives the following output:


       
d5e5 109 Master Poster

Thanks for the explanation. I tried today to come up with a solution but so far this stumps me. Does anyone else know how to do this?

d5e5 109 Master Poster

Can you tell us the rule for generating two hex values for the 31-bit conversion? Your example looks like the first value for the 31-bit conversion is identical to the result of the 32-bit conversion, and the second value is created by adding one to the first value. Is that the rule?

Assuming the above rule for 31-bit conversion, the following should give the results given in your example:

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

my @examples = ('255.102.25.02/32', '255.102.25.02/31');
my @results;

foreach my $example(@examples){
    my ($ip, $bits) = split /\//, $example;
    if ($bits == 32){
        push @results, convert32($ip);
    }
    else {
        push @results, convert31($ip);
    }
}

my $i = 0;
foreach(@examples){
    my $string = join(', ', @{$results[$i++]});
    print "$_ ==> $string\n";
}

sub convert32{
    my $ip = shift;
    my @octets = split /\./, $ip;
    my $result;
    my @arr;
    foreach (@octets){
        $result .= sprintf("%02X", $_);
    }
    push @arr, $result;
    return \@arr;#Reference to array
}

sub convert31{
    my $ip = shift;
    my @arr;
    #The first value
    my $firstvalue = convert32($ip);
    push @arr, @$firstvalue;
    
    #The second value
    my $val2 = sprintf('%08X', hex($$firstvalue[0]) + 1);
    push @arr, $val2;
    return \@arr;#Reference to array;
}
d5e5 109 Master Poster

Dear All,

Can anybody tell me how to autoincrement the Hexa decimal value.

For Ex:

I am having the value FF0B in Result array and want increment it to FF0C. Now Result array should contain two values.

(I assume you mean 'increment' because I think 'autoincrement' refers to database table columns.) When you increment a hex string the result is an ordinary decimal number which you have to reformat as a hex string if that's what you want.

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

#Create results array containing one value
my @results = ('FF0B');

#Add 1 to first element and format as hex string for second element
push @results, sprintf('%04X', hex($results[0]) + 1);

#Results array now contains FF0B, FF0C
print 'Results array now contains ', join(', ', @results), "\n";
d5e5 109 Master Poster

Thank you very much :) but can some one tell me how to proceed with 31 bit convertion.

Can you tell us the rule for generating two hex values for the 31-bit conversion? Your example looks like the first value for the 31-bit conversion is identical to the result of the 32-bit conversion, and the second value is created by adding one to the first value. Is that the rule?

d5e5 109 Master Poster

You have declared $baz with the my function which limits the scope of $baz to the block in which it is declared thus making it impossible to obtain its value from outside that block. A my declares the listed variables to be local (lexically) to the enclosing block...

In the following script I changed the my to our and deleted the statements not necessary for defining $baz and referring to its value from outside the package:

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

{ package example;
    our $baz = "sometext";
}

print $example::baz;
d5e5 109 Master Poster

I don't understand the 31 versus 32 bit distinction well enough to give a complete solution but here is a partial one:

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

my @examples = ('255.102.25.02/32', '255.102.25.02/31');
my @results;

foreach my $example(@examples){
    my ($ip, $bits) = split /\//, $example;
    if ($bits == 32){
        push @results, convert32($ip);
    }
    else {
        push @results, convert31($ip);
    }
}

my $i = 0;
foreach(@examples){
    print "$_ ==> $results[$i++]\n";
}

sub convert32{
    my $ip = shift;
    my @octets = split /\./, $ip;
    my $result;
    foreach (@octets){
        $result .= sprintf("%02X", $_);
    }
    return $result;
}

sub convert31{
    #This subroutine needs more work
    my $ip = shift;
    #I don't know the rules for converting a 31-bit ip
    return "I don't know how to convert $ip/31";
}
d5e5 109 Master Poster

<form name="login" action="$cgidir?action=verify_login" method="POST"> The above doesn't look right to me. To get it to work I put it in an html document like the following:

<html>
<header>
<title>Post form example</title>
</header>
<body>
<form name="login" action="/cgi-bin/verify_login" method="POST">
    <input type="text" name="user">
    <input type="password" name="pass">
    <input type="submit" name="login" value="Login">
</form>
</body>
</html>

Then your verify_login can read what the form POSTed by using the CGI module and its param method.

#!/usr/bin/perl
#/cgi-bin/verify_login
use strict;
use warnings;

use CGI qw(:standard);
my $cgi=new CGI; #read in parameters

print $cgi->header(); #print a header
print $cgi->start_html("Welcome"); #generate HTML document start
print "<h1>Welcome, ",$cgi->param('user'),". Your password is ",$cgi->param('pass'),"</h1></p>";
print "But I won't tell anyone.</p>";
print $cgi->end_html();#finish HTML document
roswell1329 commented: Consistently clear and useful posts. +4
d5e5 109 Master Poster

list ($h0, $h1, $h2, $h3, $h4, $h5, $h6, $h7, $h8, $h9, $h10, $h11) = split (/\t/); There is no built-in function in Perl called 'list' so it looks like you are calling a subroutine named list but you haven't defined a subroutine with that name. You need something like:

sub list{
    #Called with 11 scalar parameter
    #Does something with these parameters
    #And returns some value(s)?
    my @fields = @_;
    return 'Thanks for the parameters';
}
d5e5 109 Master Poster

It [single-payer] also inevitably leads to massive bureaucracies to manage the money...

Not nearly as massive as the combined resources of the multiple insurance companies managing thousands of insurance plans with different rules for what is and is not a reimbursable expense, as is the case for the multi-payer system in the US.

Here in Canada health-care workers know pretty well what sort of care will be covered but in the USA they cannot. If you want to know if you can afford some medical procedure that your doctor recommends, ask the appropriate bureaucrat at your insurance company.

d5e5 109 Master Poster

There are some errors I can't fix, because I don't understand what you're trying to do. For example in line 27 you declare and use $h1numeric as a scalar variable, but in line 61 you refer to an element $h1numeric[$testnumeric] as if @h1numeric is supposed to be an array variable. It's possible to declare a scalar and an array variable that both have the same name, but it would lead to confusion.

d5e5 109 Master Poster

Global symbol "@h1numeric" requires explicit package name at hairpinvsESTlocation.pl line 61. You have a lot of errors like the above. To avoid causing these errors you need to declare any lexical (i.e. non-global, non-package) variable the first time you refer to it, and you need to understand the scope of lexical variables. If you declare a variable in one while loop it will not be available in a different while loop unless you declare it again because it will have gone out of scope. To understand declaration of lexical variables and their scope I recommend you read "Coping With Scoping" by Mark Jason Dominus.

d5e5 109 Master Poster

You are missing a semicolon at the end of line 17, so perl doesn't know the statement has ended and goes blundering on, failing to understand some of the following statements which causes more error messages.

d5e5 109 Master Poster
#Do not try to declare an array element
#my $hairpin_test1[$h1numeric] = $h8; #ERROR

#Instead declare the array first and assign values to elements, as needed.
my @hairpin_test1;#Declare an array
$hairpin_test1[$h1numeric] = $h8; #Assign a value to one of the array elements
d5e5 109 Master Poster

sample data was copied and pasted - in gedit there are tabs between columns, but here it appears as spaces.

If you click the "Manage Attachments" button you can attach your input file so that it preserves all the data correctly. You may need to add an acceptable file extension (such as .txt) to your file name so you can attach it to your post.

An alternative is to wrap the contents of your file in [CODE=text]data goes here [/code] tags in your post.

Your script should include a use warnings; statement after the use strict; . That won't necessarily solve your problem but it's good practice always to use both the strict and the warnings pragmas to get helpful information about errors or possible oversights. while <($h)> { is wrong. Should be while (<$h>) {

d5e5 109 Master Poster

Add the following statement before the line where your first error occurs, (i.e. before line 8): my $proteinfilename; You should always declare lexical variables the first time you refer to them. This is what my does.

d5e5 109 Master Poster

You are opening a file without testing if the open was successful. Add an 'or die..' and error message to your open statement so you will know if your open statement failed and have some clue why it didn't work.

Also, you are assuming your file contains only one line of data. In the following, I read and print in a loop while there are any records in the file that I have not already printed.

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

# The filename of the file which contains the protein sequence
my $proteinfilename = 'NM_021964fragment.pep';#File is in my current working directory

#First open the file and associate a filehandle with it.
#For readability and more modern style lets name the filehandle $fh
#and use the 3-parameter version of the open statement.
open(my $fh, '<', $proteinfilename) or die "Failed to open $proteinfilename: $!";

print "Here is the protein:\n\n";
# Now we do the actual reading of the protein sequence data from the file,by using < > to get
# input from the filehandle. We store the data into variable $protein.
# In case there is more than one record in the file, read and print each
# record in a while loop.
while (my $protein = <$fh>){
    #Print the protein onto the screen
    print $protein;
}

#now that we got our data we can close the file
close $fh;

exit;
d5e5 109 Master Poster

Looks like your loop is calling alarm multiple times. Only one timer may be counting at once. Each call disables the previous timer...

d5e5 109 Master Poster

Rather than struggle to compose one regex that does all the substitution I would use two regexes. I find it easier to understand and change if necessary.

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

my @words = qw(iodine Thiodi number dix Iodic iodide);

foreach my $word(@words){
    $word =~ s/(?<!io)di/deu/i;#Replace di with deu unless preceded by io
    $word =~ s/(?=thio)di/deu/i;#Replace di with deu if preceded by thio
    print "$word ";
}
print "\n"; #iodine Thiodi number deux Iodic iodide
d5e5 109 Master Poster

Are you talking about colour die or death? Please reiterate your question.

The colour 'dye' is easily distinguishable from the action 'die' by the spelling. No need to disambiguate the 'die' but if you must reiterate, change the 'from' to 'to'.

d5e5 109 Master Poster

Sometimes surviving a disaster is worse than dying from it.

I remember Marilyn vos Savant once wrote a reply to a similar question by explaining why she would refuse immortality if she had the option. She reasoned that in an unlimited span of time, everything that could possibly happen to you would happen, including all possible disasters. I think its normal to fear the future to some extent.

d5e5 109 Master Poster

The best at what? Best communist country? Might be, I don't know. But I hear people in Russia have very limited food in their stores with long lines to buy anything. That's what I hear from here.

>>Could you please explain how this can be when the gap between the rich and poor continues to expand rapidly in the USA

Yes, I can explain it in just one word -- Obamacare. I didn't say USA is becoming a perfect socialist nation, just heading in that direction, and have been since 1965 with President Lyndon Johnson's "Great Society" program, which is nothing more than redistribution of wealth. And Obamacare will be much the same because it will eventually cost the tax payers trillions of dollars.

My understanding of Obamacare is that it includes no public option so the trillions of taxpayer dollars will pay the big insurance corporations. I don't see this as socialism. It continues the trend of the rich (insurance companies, so-called 'non-profit' hospitals, etc.) getting richer and the majority of the taxpayers getting poorer.

No, I don't want Communism. But I think many single-payer health care systems in Scandinavia and UK have better results than the USA does with less total cost.

d5e5 109 Master Poster

As far as I'm concerned, there is nothing but oblivion. Some may see this as horrible, but I reckon I'm entitled to a bit of rest after squeezing every drop out of this mortal coil. Jeez, I sound like a solenoid! I live life to the full and I'll get all the rest I need when I'm dead. Sounds fine to me.

How do these religious nuts sell an afterlife? Is it like an aftertaste or the pain that goes with aftershave? Is it eternal? What if you don't like it (I'm not talking just about the place that singes your arse)? You can't get off the ride, coz it's forever. Can't think of anything worse. "Here we pray on the hour every hour and read extracts from the Bible". Or some will promise a shed load of virgins. Well, they can't be virgins more than once can they? That'll be a short-lived sweetener then.

Phaff. Gimme oblivion any day.

I think religions sell their accounts of the afterlife to people who already suspect there is some kind of afterlife that they won't like and so are receptive to being told there are ways of improving their prospects.

Gimme oblivion any day.

Me too. I wouldn't mind oblivion, especially if there will be no 'me' to mind it. I just have a hard time convincing myself that eternal oblivion is what follows death. That doesn't prove that there's an afterlife, of course. Based on my experience, I just don't …