?
Solved

Generate a random number and remove from stored txt file.

Posted on 2003-03-18
5
Medium Priority
?
158 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
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

800 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