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
How to append system date to a filename in perl ?
As i am very new to perl programming , can you give me a simple example for the above query.
The strftime() function from the POSIX module gives an easy way to get a date in whatever format you want.
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use POSIX 'strftime';
my $date = strftime '%Y-%m-%d', localtime;
say $date;
You can then use that string in the filename of your file. If you are renaming a file, then you can use move() from the File::Copy module.
This might help u out!
#!/usr/bin/perl
my $date=`date +%Y%m%d`;
chomp($date);
my $source_file="/tmp/fileName_.tgz";
my $destination_file="/misc/fileName_" . $date . ".tgz";
print "$source_file\n";
print "$destination_file\n";
system("sudo mv /tmp/fileName_.tgz /misc/fileName_$date.tgz");
or try this
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
my $out = "$dir/$host-$mday-$mon-$year"
or this one
# grab the current time
my #now = localtime();
# rearrange the following to suit your stamping needs.
# it currently generates YYYYMMDDhhmmss
my $timeStamp = sprintf("%04d%02d%02d%02d%02d%02d",
$now[5]+1900, $now[4]+1, $now[3],
$now[2], $now[1], $now[0]);
# insert stamp into constant portion of file name.
# the constant portion of the name could be included
# in the sprintf() above.
my $fileName = "File$timeStamp.log";
Related
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 5 years ago.
Improve this question
I'm asking about most simple way to
Get www content (with curl I think)
Search and replace text with tree regular expression (s/a/b/; and s/as/da' etc)
Must I define variables every time when I want use a Perl command? In bash I piped the output from curl:
curl www.google.pl | sed 's/a/b'
I want to omit of these $dupa lines
$#!/usr/bin/perl
$dupa = `curl -s https://api.binance.com/api/v1/ticker/allPrices`;
$dupa =~ s/"},\{"/\n/g;
$dupa =~ s/":"/=/g;
$dupa =~ s/","/\n/g;
$dupa =~ s/\[{"//g;
print $dupa;
Always use strict in Perl code. No exceptions!
Don't shell out to curl to make an HTTP request. Use a Perl module like LWP::Simple.
The data you are downloading is JSON. Don't manipulate it as a string; use a JSON parser, like JSON::XS, to convert it to a data structure.
Here's a start:
use strict;
use LWP::Simple qw( get );
use JSON::XS qw( decode_json );
use Data::Dumper qw( Dumper );
my $data = decode_json(get("https://api.binance.com/api/v1/ticker/allPrices"));
print Dumper($data);
You can now manipulate the data structure in the $data variable; for instance:
for my $item (#$data) {
print "$item->{symbol} : $item->{price}\n";
}
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 8 years ago.
Improve this question
I use the below code to handle upload file through perl cgi. I try fileparse but gives path error. What am I doing wrong here?
exec fail through below error.
fileparse(): need a valid pathname at ./testupload.cgi line 15
Any inputs?
Source:
use strict use CGI;
use CGI::Carp qw ( fatalsToBrowser );
use File::Basename;
$CGI::POST_MAX = 1024 * 5000;
my $safe_filename_characters = "a-zA-Z0-9_.-";
my $upload_dir = "/home/test/Desktop/uploads";
my $query = new CGI;
my $filename = $query->param("textfile");
my ($name, $path, $extension) = fileparse($filename, '\..*');
$filename = $name.$extension; $filename =~ tr/ /_/;
$filename =~ s/[^$safe_filename_characters]//g;
if ($filename =~ /^([$safe_filename_characters]+)$/)
{ $filename = $1; }
else
{ die "Filename contains invalid characters"; }
Looking at the source for File::Basename, it seems that you'll only get that error message if you pass an undefined value as the first argument to fileparse(). So it definitely looks like $filename is undefined. Which means that your line:
my $filename = $query->param("textfile");
Isn't doing what you think it is. Perhaps you're not passing a value for that CGI parameter. Perhaps you've got the name of the form input wrong. But without seeing how you are calling your program, it's impossible to be any more help.
A few more comments on your code:
use strict use CGI; - presumably this gives a syntax error
Please use CGI->new in place of new CGI
The second (and subsequent) arguments to fileparse() should be file extensions. \..* doesn't look much like a file extension to me
You remove all of the unsafe filename characters from $filename and then check to see if there are any unsafe filename characters in $filename. Is that really what you intended?
And then there's the standard advice that learning CGI in 2014 is a lot like learning to use a typewriter. It'll work, of course, but people are going to think you're a bit old-fashioned and strange :-)
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 9 years ago.
Improve this question
Can anyone tell me why I'm getting this:
usage: gen-non-random.pl <count> <outputfile>
From the code below:
#!/usr/bin/perl -w
#
# Script to generate non random values, to demonstrate a bad randomness graph
# for my "Howto Analyse SessionIDs".
#
# written by:
$version = "0.0.4";
$filename = "gen-non-random.pl";
$usage = "usage: $filename <count> <outputfile>\n";
$count = $ARGV[0] or die ("$usage\n");
$output = $ARGV[1] or die ("$usage\n");
print ("-- $filename Version: $version\n");
use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
use Math::Random;
use Digest::MD5 qw(md5_hex);
open (OUT, ">$output") or die ("Can't open $output\n");
for ($i=0; $i<$count;$i++)
{
# generate a random number
$random = random_uniform();
# cut out char 3-9 of $random and put it in $randsub
$randsub = substr($random, 2, 6);
# get seconds and microseconds since epoch
($seconds, $microseconds) = gettimeofday;
# get the last two chars of the seconds and put them into $s
$s = substr($seconds, 8, 2);
# sleep for a while
usleep $randsub;
# put together the last two digits of seconds and the microseconds
$time = $s . $microseconds;
$md5_time=md5_hex($time);
# print out the stuff we put together above
print OUT ("$md5_time\n");
}
close (OUT) or die ("Can't close $output\n");
print ("$count values written to $output\n");
exit;
I am new to programming so i need really simple answer please! I do not own this code I am using for my research paper at University. Also, could someone please explain to me what Usage actually is i can't seem to find a good explanation for it?
Thanks.
You're getting that error because you're not using the program correctly:
usage: gen-non-random.pl <count> <outputfile>
This basically means you have to provide a count and output file as arguments, such as:
perl gen-non-random.pl 42 outfile.txt
This will generate forty-two numbers and output them to the outfile.txt file.
It's the two lines near the start, checking ARGV[0/1] and die-ing if you don't provide them, that are outputting this message and exiting the program.
Hmmm. I can't run the above code because Time::HiRes::ualarm() is not implemented on Windows. That said, it appears to be generating a MD5 has string of the current time (in integer form) after sleeping for a random number of seconds, then dumping the result into a text file. You are getting the usage message mentioned above because the program expects input. Try running it from the command line like so:
perl gen-non-random.pl 10 MyResults.txt
I suspect that will dump 10 HD5 hash results into a file called "MyResults.txt".
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
How can I change the format of dates 12/23/02 to 23/12/2002 or 03/35/55 to 35/03/2055?
I can read the dates from text file but I can't change their format:
15/06/17 ====> 06/15/2017
Here's the example using DateTime::Format::Strptime:
UPDATE:
use DateTime::Format::Strptime;
my $str = '12/23/02';
my $parser = DateTime::Format::Strptime->new( pattern => '%m/%d/%y');
my $dt = $parser->parse_datetime( $str );
print $dt->strftime('%d/%m/%Y')
output:
23/12/2002
I think the Perl Module Time::Piece should work
use Time::Piece 'strptime';
my %date = strptime('%d/%m/%y', '15/06/17');
The date hash contains then the parsed date elements, $date{d}, $date{m}, and $date{y} which you can use to reformat the date.
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);