How do I remove a random value from an array in Perl?

I am learning Perl and creating an application that gets a random string from a file using this code:

open(my $random_name, "<", "out.txt");
my @array = shuffle(<$random_name>);
chomp @array;
close($random_name) or die "Error when trying to close $random_name: $!";
print shift @array;

      

But now I want to remove this random name from the file. How can i do this?

+2


source to share


3 answers


  • shift

    already removes the name from the array.

    So, pop

    (one from the beginning, one from the end) - I would suggest using pop

    as it might be more efficient and be random, you don't care what you use.

  • Or do you need to remove it from the file?

    In this case, you need:

    and. get the number of names inside the file (if it is small, read everything in memory with help File::Slurp

    , if it is large, either read it one by one, or count or just execute the command wc -l $filename

    through the backreferences.

    B. Generate a random # from 1 to <$ strings> (say $random_line_number

    C. Read the file line by line. For each line, read WRITE in a different temporary file (use File::Temp

    to create temporary files. Except DO NOT write the line numbered $random_line_number

    to a text file

    E. Close temp file and move it instead of original file

  • If the list contains a file and you need to delete the file itself (random file) use the function unlink()

    . Remember to process the return code from unlink()

    and, as with any I / O operation, print an error message containing $!

    what will be the system error text on failure.

Done.



D.

+4


source


When you say "remove this ... from the list" do you want to remove it from the file? If you just want to remove it from @array

, then you already did it using shift

. If you want it to be removed from the file, and the order doesn't matter, just write the remaining names in @array

back to the file. If the order of the files matters, you will need to do something a little more complex, like reopening the file, reading the items in order except the one you don't want, and then writing everything back out again. Either that, or pay attention to the order when you read the file.



+2


source


If you need to remove a line from a file (which is not entirely clear from your question), one of the simplest and most effective ways is to use Tie :: File to manipulate the file as if it were an array. Otherwise, perlfaq5 explains how to do it a long way.

+1


source







All Articles