KevinADC 192 Practically a Posting Shark

Hi Guys,
Can any one suggest to generate a random number of eight digit.
All suggestions are welcomed :)

http://www.daniweb.com/code/snippet216771.html

A search engine would also find many examples of code to do what you are asking.

KevinADC 192 Practically a Posting Shark

If you do that you can only have 7 strings of random numbers. What you want to do is much easier than the code I posted. All you have to do is shuffle an array of numbers and then split the array into strings of n length (7 in this case). You can use List::Util to shuffle the array and a loop to assign the numbers to strings, something like:

use strict;
use warnings;
use List::Util 'shuffle';
my @nums = shuffle(1..49);
my @rand_nums;
for (my $n = 0; $n < 48; $n+=7) { 
   push @rand_nums, join('-',@nums[$n..$n+6]);
}
print "$_\n" for @rand_nums;
KevinADC 192 Practically a Posting Shark

The code already produces unique strings of random numbers so I am not sure what you are asking.

KevinADC 192 Practically a Posting Shark

This code snippet will produce strings of numbers (1 thru 49) with no repeated numbers in the same string and no duplicated string of numbers in the list of strings. To change the range of numbers the script generates change 49 in the code to your requirements.

Please feel free to ask questions or post comments about this snippet of code.

KevinADC 192 Practically a Posting Shark

You should put all the code in the same post. In your function you should use if/elsif/else instead of if/if/elsif.

KevinADC 192 Practically a Posting Shark

Image-Size has dependencies, so adding it via the lib pragma may not work unless the depenedencies are also added.

It is a good way though to get image dimensions.

KevinADC 192 Practically a Posting Shark

It probably is a bit cryptic. But code is that way if you don't understand the syntax of a particular language. It could be written very cryptically as a one-liner. Something like (unchecked for accuracy):

perl -i.bac -ne "next if ++$seen{$_}>1; print;" file.txt
KevinADC 192 Practically a Posting Shark

A bare-bones code snippet to remove duplicate lines from a file. There are a number of ways to accomplish this task but this is a fast and dependable method using perls inplace editor and a simple hash to get the job done.

This probably should not be used for really big files, but files with a few thousand lines or even a few tens of thousands of lines should be OK. The bigger the file, the longer it may take to run.

d5e5 commented: I was looking for an example of using inplace editing without having to put the filename on the command line and there it was: local anonymous block and local @ARGV. Thanks. +1
KevinADC 192 Practically a Posting Shark

This is a bare-bones search and replace script that uses perls in-place editor and the File::Find module to get the job done quickly. It will search in all sub directories of the start directory and find and replace the text you specify in the type of file you specify. Keep in mind, this is a bare-bones implementation that is more for learning than for pratical use. It could be altered to accept command line arguments, input from the keyboard, or run as a CGI. That is up to you to figure out. :cheesy:

KevinADC 192 Practically a Posting Shark

good information

KevinADC 192 Practically a Posting Shark

Given the date in mm-dd-yyyy (or M-D-YYYY) format (or any combination of that format) you can find out what day of the week that was on or is on or will be on, within the limitations of the system the script resides on.

This snippet uses only core functions and modules so nothing needs to be installed but it is worth mentioning that there are numerous date modules on CPAN that offer a wide range of functions for handling date calculations.

http://search.cpan.org/search?query=date&mode=all

This snippet assumes the date is in mm-dd-yyyy format but can easily be adapted to handle any combination of those date parameters. Can also handle years in three digit and two digit format but see the Time::Local and localtime() documentation for limitations.

leo002000 commented: 3 +3
KevinADC 192 Practically a Posting Shark

Looks like an error/typo in this line:

unless (flag1 == 0) {die("Cannot open visitor_stat.txt");}

missing the '$' before flag1, should be:

unless ($flag1 == 0) {die("Cannot open visitor_stat.txt");}

KevinADC 192 Practically a Posting Shark

foobie,

excellent post and a good observation about my flawed test.

Regards,
Kevin

KevinADC 192 Practically a Posting Shark

Yes, but benchmarking the two differnt ways is revealing:

my $string = "    Mary had a little lamb.   ";

my  $results = timethese(200000, 
        {
            'First' => sub {$string =~ s/^\s*//;$string =~ s/\s*$//;},
            'Second' => sub {$string =~ s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;}
        },
    );
cmpthese( $results ) ;

results:

Benchmark: timing 200000 iterations of First, Second...
     First:  1 wallclock secs ( 2.25 usr +  0.00 sys =  2.25 CPU) @ 88888.89/s (n=200000)
    Second:  3 wallclock secs ( 3.73 usr +  0.00 sys =  3.73 CPU) @ 53619.30/s (n=200000)
          Rate Second  First
Second 53619/s     --   -40%
First  88889/s    66%     --

using two regexps is 66% percent faster (on my computer, results will vary).

KevinADC 192 Practically a Posting Shark

This is a routine task best done with two regexp's when using perl.

KevinADC 192 Practically a Posting Shark

In the above code the first line should be:

my $number = 1000000;

KevinADC 192 Practically a Posting Shark

Convert 1000000 into 1,000,000 using a perl regexp.

KevinADC 192 Practically a Posting Shark

Use the List::Util module. I believe List::Util is a core module starting with perl 5.8. For older versions of perl you may need to install the module. See the module documentation for more details: List::Util

KevinADC 192 Practically a Posting Shark

I've seen this question (or similar) asked many times on forums:

I have a variable in a file (text) and want to expand it. For example, I have this line in a text file:

Mary had a little $lamb

and I want to be able to expand $lamb but text files are treated as single-quoted strings and perl does not interpolate variables in single-quoted strings.

KevinADC 192 Practically a Posting Shark

"How can I find all the permutations of a list (or a word)"? I have seen this question asked a number of times on forums. There is a module that makes this task very easy: List::Permutor. It is not a core module so you may need to install it. See module for more details: List::Permutor

KevinADC 192 Practically a Posting Shark

You will need to install the Email::Valid module if it's not already installed. See the module documentation for further details.

Email::Valid

KevinADC 192 Practically a Posting Shark

Code snippet to generate random passwords. Avoids using confusing characters such as lower case L (l) and the number one (1), the letter 'O' and the number zero. Upper-case alpha characters could be added to the character set if mixed-case passwords are desired.

KevinADC 192 Practically a Posting Shark

The File::Basename module is used to parse file paths into directory, filename and suffix (or file extension). My simple example shows how to get just the file extensions.

KevinADC 192 Practically a Posting Shark

Mike,

Like I said, don't bother with the + file open operator, use Tie::File or perls inplace editor. And why are you using "while (<@slurp>)" instead of "for(@slurp)". Its a little bit frustrating when I take the time to make suggestions and try to help a person and explain things to them but they seem to ignore what I have said.

KevinADC 192 Practically a Posting Shark
# Rewrite of kevin code, why don't this work?
open (INFILE, '<', $ARGV[0]) or die "Error writing to $ARGV[0]: $!\n";
@slurp = <INFILE>;
for ( @slurp )
{
    s#<(/?)H1>#<$1H2>#g;
    print INFILE $_;
}
close INFILE;

The above doesn't work because "<" is the operator to open a file in read-only mode.

KevinADC 192 Practically a Posting Shark

Your code does not work to edit the file because as was explained to you on perlguru you have opened the file for reading only. That is why I open it a second time as explained in the comments in the code I posted. You can try a file opening operator that allows you to read and write to a file at the same time, its either "+>" or ">+" I don't remember which.

You should use a "for" loop to process an array, not a "while" loop. "for" and "foreach" are optimized for the purpose of looping over an array, "while" is not.

Edit:

forget the +> and >+ suggestion. Read this for explanation:

http://perldoc.perl.org/perlopentut.html#Mixing-Reads-and-Writes

Here is the final word: use Tie::File or perls inplace editor if you want to edit a file in one pass.

KevinADC 192 Practically a Posting Shark

Mike,

You have several very good replies on perlguru but here is your code rewritten to work:

[I]# first open file for reading only[/I]
open (INFILE, $ARGV[0]) or die "Error $ARGV[0]: $!\n";
@slurp = <INFILE>;
close(INFILE);

[I]#now open file for overwriting[/I]
open (OUTFILE, ">", $ARGV[0])  or die "Error $ARGV[0]: $!\n";
for (@slurp){
   s#<(/?)H1>#<$1H2>#g;
   print OUTFILE;
}
close OUTFILE;
KevinADC 192 Practically a Posting Shark

You already got a script on another forum so I will drop out of this thread

KevinADC 192 Practically a Posting Shark

You should just append a date to the end of the log file then you don't need to rename all the other files every time the script runs.

KevinADC 192 Practically a Posting Shark

Check the Windows server 2003 error logs. Hopefully there is something in the log that can help.

Before you ask how, search google:

http://www.google.com/search?q=Windows+server+2003+error+logs

KevinADC 192 Practically a Posting Shark

Do the groups of lines with numbers break at the lines with text? In other words, do you only sort the numbers up to "test" as a group, and then sort the next set of lines with numbers until the next line with "test" or does the sorting of the numbers need to be done as one continuous group?

If the lined numbers are discrete groups you can continue storing them in an array until you get to a line with text. You then sort the group of numbers and print them to a file and then print the line of text last, or push it all into a larger array and continue like this this until the entire file is read and sorted.

If the entire file needs to be sorted yet the lines with text need to stay in their original position you will need to store the position (the line number I guess) in a hash, then sort all the numbered lines, then print the sorted numbers back to the file but keeping track of the line numbers as you go and insert the text back as needed.

But one thing I am pretty sure of, you will not be able to accomplish this with a single sort.

KevinADC 192 Practically a Posting Shark

I guess you didn't read what exec() does.

The exec function executes a system command and never returns-- use system instead of exec if you want it to return

http://perldoc.perl.org/functions/exec.html

As they say on forums: Read the manual

If you want to run multiple instances of a perl program I think you will want to use threads. Not something I have experience with though:

http://search.cpan.org/~jdhedden/threads-1.74/threads.pm

KevinADC 192 Practically a Posting Shark

Calling another perl script in a loop should not be difficult but the last part of your question makes no sense to me.

I want the second calling of the script shouldn't depend on the first calling.... all should run independently............

KevinADC 192 Practically a Posting Shark

you're welcome

KevinADC 192 Practically a Posting Shark

considering the thread is almost a year old.......

KevinADC 192 Practically a Posting Shark

i'm sure 'file' is absolutely valid)

cool, for the last 2 and a half years I've been wondering about that..... :-/

KevinADC 192 Practically a Posting Shark

use sprintf to round off your numbers.

my $t = 92.38495;
$t = sprintf ("%.0f", $t);
print $t;
KevinADC 192 Practically a Posting Shark

It aborts because you can't have nested quantifiers.

Your expectation of what the "g" modifier does is also wrong. Here is an excerpt from perlretut:

Global matching

The final two modifiers //g and //c concern multiple matches. The modifier //g stands for global matching and allows the matching operator to match within a string as many times as possible. In scalar context, successive invocations against a string will have `//g jump from match to match, keeping track of position in the string as it goes along. You can get or set the position with the pos() function.

The use of //g is shown in the following example. Suppose we have a string that consists of words separated by spaces. If we know how many words there are in advance, we could extract the words using groupings:

1. $x = "cat dog house"; # 3 words
2. $x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
3. # $1 = 'cat'
4. # $2 = 'dog'
5. # $3 = 'house'

But what if we had an indeterminate number of words? This is the sort of task //g was made for. To extract all words, form the simple regexp (\w+) and loop over all matches with /(\w+)/g :

1. while ($x =~ /(\w+)/g) {
2. print "Word is $1, ends at position ", pos $x, "\n";
3. }

prints

1. Word is cat, ends at position 3
2. Word …

KevinADC 192 Practically a Posting Shark

You need parentheses for back references to capture patterns they find.


if (/($pattern)/) {

KevinADC 192 Practically a Posting Shark

hashes are not randomly ordered lists, they are lists that don't have any guaranteed ordered, but they should always be the same order on the same computer. So that bug report appears to be erroneous because the reporter did not seem to understand that hashes are not randomly ordered.

If you need to use a hash, you can store the keys in an array and use List::Util and the shuffle function to randomly order the array with the hash keys. Then loop over the array instead of the hash. An example:

use List::Util qw/shuffle/;
my @keys = (1..26);
my @values = ('a'..'z');
my %hash;
@hash{@keys}=@values;

@keys = shuffle(@keys);
for(@keys){
    print "$hash{$_}\n";
}
KevinADC 192 Practically a Posting Shark

Normally in perl you don't worry about memory management. But instead of undef you can assign the variable an empty list/string and see if that helps free up memory.

$var = '';
@var = ();
%var = ();

KevinADC 192 Practically a Posting Shark

What are you entering into $pattern?

KevinADC 192 Practically a Posting Shark

I assume you are shelling out because you don't know who to write it all in perl. Here is one way:

#!/usr/bin/perl -w
#for folders 41..60
open (my $OUT, ">>", "path/to/output1") or die "$!";
for my $k (41..61){
   opendir(my $DIR, "Users/scripts/$k") or die "$!";
   my @files = grep {/^ms_stem/} readdir $DIR;
   close $DIR;
   foreach my $file (@files) {
      open(my $FH, "<",  "Users/scripts/$k/$_") or die "$!";
      while(<$FH>){
         print $OUT $_ if /word/;
      }
      close($FH);
   }
}

This should be more efficient than starting a new process for each directory you are scanning over. The only thing I am not sure of is what you wanted to print to output1 if you locate "word" in the file. The line of the file (which my code should do) or the name of the file or the line number or what?

KevinADC 192 Practically a Posting Shark

or using a loop:

use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $success = 1;
for (1..5) {
   my $req = $ua->get( 'http://some.web.site');
   if ($req->is_success) {
      print $req->content;
      $sucess = 0;   
      last;
  }
}
unless ($sucess) {
    print "Failed all 5 tries to get content\n";
}
KevinADC 192 Practically a Posting Shark

typically you would use the CPAN shell to install modules with Linux. This part of the perl documentation should help you:

http://perldoc.perl.org/perlmodinstall.html

Note it is written for perl 5.10 which might differ from earlier version of perl.

KevinADC 192 Practically a Posting Shark

You never said what error you were getting but I am assuming you were getting a warning and not an array.

Scalar value @array[$marker] better written as $array[$marker] at script line 9 .

When accessing individual elements of an array you use the scalar data type symbol $ and not the list/array data type symbol @.

But perl has 'for' and 'foreach' loops to loop through an entire array or you should use the perlish style of indexed looping:

#!/usr/bin/perl -w
use strict;

my @array = (10, 20, 30, 40, 50, 60);

for my $i (0..$#array){
   print "$array[$i]\n";
}

indexed looping is really only necessary when you don't need to loop through an entire array or might want to skip over the odd or even elements of an array, otherwise use for/foreach (which are the same).

KevinADC 192 Practically a Posting Shark

use eval unless you really want to think of perl like C.

http://perldoc.perl.org/functions/eval.html

I assume the module is just a wrapper around eval but I haven't looked at the source code.

KevinADC 192 Practically a Posting Shark

Perl has no such inbuilt functions/operators try and catch.

KevinADC 192 Practically a Posting Shark

I'm going to suggest you ask this question on www.unix.com in the shell scripting forum:

http://www.unix.com/shell-programming-scripting/

KevinADC 192 Practically a Posting Shark

anywhere you are opening a file in the script:

open(USERLIST, "./User Lists/$infile.csv");\

change to:

open(USERLIST, "./User Lists/$infile.csv") or die "Can't open ./User Lists/$infile.csv: $!";

just make sure to put the name of the file in the die part that corresponds with the actual file being opened. Rerun the script and see if die returns an error associated with opening a file.

And please use the code tags for all future postings of code.