Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to write a CGI script that will take three lines of text and randomize them. Each time you view the webpage, the three lines will appear one after the other in a different order each time. How do I do this and what is the code?
perldoc -q "random line"
Found in D:\sb\perl\lib\perlfaq5.pod
How do I select a random line from a file?
Short of loading the file into a database or pre-indexing the lines in
the file, there are a couple of things that you can do.
Here's a reservoir-sampling algorithm from the Camel Book:
srand;
rand($.) < 1 && ($line = $_) while <>;
This has a significant advantage in space over reading the whole file
in. You can find a proof of this method in *The Art of Computer
Programming*, Volume 2, Section 3.4.2, by Donald E. Knuth.
You can use the File::Random module which provides a function for that
algorithm:
use File::Random qw/random_line/;
my $line = random_line($filename);
Another way is to use the Tie::File module, which treats the entire file
as an array. Simply access a random array element.
or
perldoc -q shuffle
Found in D:\sb\perl\lib\perlfaq4.pod
How do I shuffle an array randomly?
If you either have Perl 5.8.0 or later installed, or if you have
Scalar-List-Utils 1.03 or later installed, you can say:
use List::Util 'shuffle';
#shuffled = shuffle(#list);
If not, you can use a Fisher-Yates shuffle.
sub fisher_yates_shuffle {
my $deck = shift; # $deck is a reference to an array
return unless #$deck; # must not be empty!
my $i = #$deck;
while (--$i) {
my $j = int rand ($i+1);
#$deck[$i,$j] = #$deck[$j,$i];
}
}
use List::Util qw( shuffle );
#lines = shuffle(#lines);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a variable $abc that contains the line like below:
abc.txt -> check a/b/c test
I need to get abc.txt in another variable say $bcd and a/b/c in the variable say $xyz. I have the regex to do so but I don't know how I can do it using perl as in my knowledge perl grep and perl map can be used on arrays only not variables.
my ($bcd) = split(/\s*->\s*/, $abc, 2);
my $bcd = $abc =~ s/\s*->.*//sr;
my ($bcd) = $abc =~ /^(?:(?!\s*->).)*)/s;
my ($bcd) = $abc =~ /^(.*?)\s*->/s;
All but the last returns the entire input string if there's no ->.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I want to write a Perl subroutine using rand() function that generates a random DNA sequence of specified length n. The length n of the sequence is passed as an argument to the subroutine.
I would appreciate if someone could help me out as I am a beginner in perl.
FYI normally you put anything that you have tried so far, Stack Overflow isn't a code writing service.
With that in mind, the best way to do this in my humble opinion is with Perl's rand function:
#!/usr/bin/env perl
use strict; use warnings;
use autodie ':all';
use feature 'say';
my #letters = qw(A C G T);
sub random_DNA {
my $length = shift;
my $seq = '';
foreach my $n (1..$length) {
$seq .= $letters[rand(4)]
}
return $seq
}
foreach my $length (1..9) {
say random_DNA($length)
}
which outputs
con#V:~/Scripts$ perl random_DNA.pl
T
TT
TGG
TGTC
ATGAC
AACGAG
CGGGGTT
CCGTCGTC
TGGCCTCGA
your output will probably not be identical to this, of course, as this is a random function. I prefer not to use modules if I can avoid them, to avoid portability issues, especially with tasks that take a minute to write, like this one.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Im taking a Bioinformatics class and I keep getting an "Undefined subroutine &main::Print called at ReverseComp.txt line 4." error
# ReverseComp.txt => takes DNA sequence from user
# and returns the reverse complement
print ("please input DNA sequence:\n");
$DNA =<STDIN>;
$DNA =~tr/ATGC/TACG/; # Find complement of DNA sequence
$DNA =~reverse ($DNA); # Reverse DNA sequence
print ("Reverse complement of sequence is:\n");
print $DNA."\n";
This is my code and I have tried a few different things with line 4 but with no results. Any suggestions? (I am writing this from a prompt, everything looks right....)
I have some notes related to your code:
Name your scripts with the .pl extension instead of .txt. That is the common accepted extension for Perl scripts (and the .pm for Perl modules, libraries with reusable code)
Always start your scripts with use strict; use warnings;. These sentences helps you to avoid common mistakes.
Declare your variables before you use it (See the my function)
chomp your input from STDIN to remove the newline at the end.
The call to reverse function is odd. I think that $DNA =~ reverse ($DNA); should be $DNA = reverse ($DNA);
The reverse function is more common used with Perl arrays; with a string you get the reversed version of that string, as I guest you expected.
The print function may take a list of parameters, so you can print several things in one sentence
You can omit parentheses in many places, e.g. reverse($a) is the same as reverse $a. Both are valid, but the latter is more suitable to the Perl style of writing code. The Perl style guide is a recommended read
Related to your question, I think your script is right, because the print function exists in Perl, and the error you got says about Print (with uppercase, which is important in Perl). You maybe run a different script that you have posted here.
This is your script with the previous considerations applied (ReverseComp.pl):
use strict;
use warnings;
print "please input DNA sequence:\n";
chomp( my $DNA = <STDIN> );
$DNA =~ tr/ATGC/TACG/; # Find complement of DNA sequence
$DNA = reverse $DNA; # Reverse DNA sequence
print "Reverse complement of sequence is:\n", $DNA, "\n";
In any case, welcome to the fantastic Perl world, and be prepared to enjoy your trip.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Why does the following script take so many cycles to complete?
The document it is sifting through is 20590 lines long and each line consists of the following, or a variation thereof;
"10160354001 ALGIERS ALGERIA 36.70 3.60 290"
I am trying to make a database to match the first number to the last 3.
The actual program is however taking several seconds per line.
Script:
#! /usr/bin/perl
$path = shift(#ARGV);
open COORDS, $path or die "Couldn't open file\n";
my %coords = {};
foreach $line (<COORDS>){
$stat = substr $line,0,11;
#coords = grep(($_!=undef),split(/ /,substr $line,42));
$coords[$stat]=#coords;
}
print $coords['10160354001'];
close(COORDS);
$coords['10160354001'] = ... is an assignment to an array element, and a large one at that. This statement will cause Perl to allocate an array with room for at least 10160354002 elements.
You meant to use a hash:
$coords{$stat} = "#coords";
...
print $coords{'10160354001'};
use strict and use warnings would have alerted you to this and other problems with your code.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a Perl script that I am using to create a file.
I have a variable that holds a number of file paths separated by commas.
path/to/file1,path/to/file2....path/tofileN
Depending on how many file paths are returned, I need to create another string that creates random strings, to match with each file up to N files
If my first string variable contains 3 file paths, I need to create a string like
RandomName1,RandomName2,RandomName3
and write it out to my output file.
How can I parse the incoming string of file paths to determine how many file paths there are in total?
How can I write a loop to create a file name for each incoming file path, upto N files?
I don't quite see why you would put the list of names into a separate string, but here we go.
use strict;
use warnings;
sub create_random_name {
# return a random filename
}
my $foo = '/home/foo,/root,/dev/null';
my #filenames;
foreach (split ',', $foo) {
push #filenames, create_random_name();
}
print join ',', #filenames;
__END__
efe277fe7aa54f7231dedef7ac8c1e3a,327f56cff4bd21b03ee3ceaa4280014c,7f1ca3feb3b51f7a9ee84f08b1791785
Let's see.
I've created a sub create_random_name that should return some randomness. Without further specification of what you need, I will leave that out of the answer.
We split your string of paths into an array, but since you do not want them, we only loop through the results. There is no my $bar in the foreach for the same reason.
We only want to create_random_name for the same number of files as there are paths. Those are pushed into #filenames,
which we then join on , to make them look the same as our starting point, the list in $foo.
For 1), you probably want split as RC said. For 2), File::Temp should do the trick.
use File::Temp 'tempfile';
my $orig_path_str = 'path/to/file1,path/to/file2....path/tofileN';
#orig_paths = split(/,/, $orig_path_str);
my #random_paths;
# loops number of times equalling your number of paths
foreach (1..scalar(#orig_paths)) {
my ($fh, $filename) = tempfile();
push(#random_paths, $filename);
}
my $random_path_str = join(',', #random_paths);