?
Solved

Generate a random number and remove from stored txt file.

Posted on 2003-03-18
5
Medium Priority
?
159 Views
Last Modified: 2010-03-05
Hi all,


I have a txt file (one.txt) that stores 1 to 49 numbers as follows:

one.txt
-------
1
2
3
4
5
.
.
49

First time if i run a program, generate a randum number b/w 1 and 49, and getting value is removed from one.txt file. How can i write a perl program for that?

Sample :- While running the program, say generated value is 26 then remove 26 from one.txt file.

Regards


0
Comment
Question by:r_kar
  • 2
  • 2
5 Comments
 
LVL 48

Expert Comment

by:Tintin
ID: 8158151
#!/usr/bin/perl
use strict;
my $rand = int(rand(49)+1);

open FILE, "one.txt" or die "Can not open one.txt $!\n";
open TEMP, ">one.temp" or die "Can not open one.temp for writing $!\n";

while (<FILE>) {
  chomp;
  next if ($_ == $rand);
  print TEMP;
}

close TEMP;
close FILE;
rename "one.temp", "one.txt" or die "Can not rename one.temp to one.txt $!\n";


Of course the above can be done as a simple one liner, but I thought it might be more useful for you to see the longer version.
0
 
LVL 1

Expert Comment

by:sureshp
ID: 8158391
I am posting a sample code.
Your major part will solve using this script.
I am inputing "4" as random generated value (instead of this u can generate a random number).

#!/usr/bin/perl
$op = "delete"; # $op eq 'delete'
@names = "4";
$datafile = "C:/del.txt" ; # change this name as needed


# set up a hash with the selected names as keys
map { print "\n";$selected{$_}++; print "\n"; } @names;

open NAMES, "+<$datafile";

@lines = <NAMES>;

seek NAMES, 0, 0;
truncate NAMES, 0;
$y = "";
foreach ( @lines ) {
    chomp $_;
   unless ( $op eq 'delete' && $selected{$_} ) {
          $y .= $_."\n";
     }
                 
 }

close NAMES; # flushes and unlocks it, too

print "Remaining Values are... $y\n";
open (HERE,">C:/del.txt");
print HERE $y;
close (HERE);

Try to modify for random generating nos. Hope that helps.
If u can't get a soln using rand function, post a comment here.
0
 
LVL 1

Expert Comment

by:sureshp
ID: 8158534
I had made two changes ...

Writing the same file format after deleting an entry.
Random Generation number...

 Hope this is your required solution.

#!/usr/bin/perl
$op = "delete"; # $op eq 'delete'
$rand = int(rand(49)+1);
print "Here... $rand\n";
@names = $rand;
$datafile = "C:/one11.txt" ; # change this name as needed


# set up a hash with the selected names as keys
map { print "\n";$selected{$_}++; print "\n"; } @names;

open NAMES, "+<$datafile";

#flock NAMES, 2; # exclude others

@lines = <NAMES>; # slurp entire file

seek NAMES, 0, 0; # rewind
truncate NAMES, 0; # prepare for rewriting
$y = "";
foreach ( @lines ) {
    chomp $_;
   unless ( $op eq 'delete' && $selected{$_} ) {
          $y .= $_."\n";
     }
                 
 }

close NAMES; # flushes and unlocks it, too

#print "Remaining Values are... $y\n";
open (HERE,">C:/one11.txt");
print HERE $y;
close (HERE);
0
 
LVL 6

Accepted Solution

by:
holli earned 200 total points
ID: 8160733
the following is a function you can just cut and paste into you script and call it at an appropriate position.

use strict;

#example call
print getRandomFromFile("d:/temp/random.dat");

sub getRandomFromFile
{
  my $infile = $_[0];
  defined $infile or die "you did not specify a file!";
  -e $infile or die "specified file does not exist!";

  open I, $infile or die "specified file could not be opened for input!";
  my @lines=<I>;
  close I;

  die "random file is empty!" unless (@lines);

  my $rand=int(rand()*$#lines);
  my $ret=splice(@lines,$rand,1);

  open O, ">$infile" or die "specified file could not be opened for output!";
  print O @lines;
  close O;

  return $ret;
}
0
 
LVL 6

Expert Comment

by:holli
ID: 8160739
sorry,

please replace

return $ret;

by

chomp($ret);
return $ret;
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question