Way to not define much variables in Perl? [closed] - perl

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";
}

Related

GetOpt Long processing similar input names [closed]

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 6 years ago.
Improve this question
I'm running a perl script with a lot of input options, one of them being:
'errorcode=s{1,}' => \#ecodes,
I have a die at the end of the GetOptions if anything entered doesn't match the input. However if I input '--ecode 500' the program runs.
Why isn't the script dying? If I try something else like '--testing 123' it does die.
I'm guessing you have a option with a required argument such as
"foo=s" => \$foo,
and that you did something like
program --foo --ecode 500
which puts --ecode in $foo and 500 in #ARGV.
$ perl -MGetopt::Long -e'
use feature qw( say );
GetOptions("foo=s" => \$foo)
or die "usage\n";
say "ok <$foo> <#ARGV>";
' -- \
--ecode 500
Unknown option: ecode
usage
$ perl -MGetopt::Long -e'
use feature qw( say );
GetOptions("foo=s" => \$foo)
or die "usage\n";
say "ok <$foo> <#ARGV>";
' -- \
--foo --ecode 500
ok <--ecode> <500>

How can I export or use a variable in 1 file to a function in another file in perl? [closed]

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 8 years ago.
Improve this question
I am very new to perl, so don't have much knowledge in perl scripting.
I have two files test1.pl and testfinal.pl.
testfinal.pl
for loop{
$var = $_;
my $out = `perl test1.pl -p $var`;
}
test1.pl
Foo();
sub Foo(){
# I want to get $var from testfinal.pl so that I can perform some functions of that perticular varaible.
$elt = `mkdir $var`;
}
I checked some links, but I found for exporting I need to make the file in '.pm' format (testfinal.pm) which is not possible as I need to get the final output but executing testfinal.pl.
Can anyone help me here quickly.Please...
Pathak has covered some fine ways of passing your information through the file system, but I also note that you've passed $var through the command line. test1.pl should already have that info in #_, specifically as $_[1].
Examples:
Foo();
sub Foo(){
$elt = `mkdir $_[1]`;
}
or better
Foo($_[1]);
sub Foo{ #prototype deleted, probably should stay that way...
my $dir = shift;
$elt = `mkdir $dir`;
}
For cleaner handling of command line parameters, the GetOpt::Long module is core.
If you aren't attached to launching a shell & a 2nd instance of the perl executable, some other approches for running 2 files as a single program are the keywords use and require. (check perldoc for details.) These approaches allow you to share package variables or to directly pass parameters to the target subrutines.
I suggest that you create a module as documented in perlmod and Exporter.
The following demonstrates how to do this with your setup:
MyModule.pm:
package MyModule;
use strict;
use warnings;
use Exporter qw(import);
sub Foo {
my $var = shift;
print "mkdir $var\n";
}
testfinal.pl:
use strict;
use warnings;
use MyModule qw(Foo);
my #array = (...);
for my $var (#array) {
my $out = Foo($var);
}
Also note that perl has a native mkdir function, so there is no need to shell out to the system for that functionality.

Perl combine MD5 / SHA2 sum from multiple files to a MD5 / SHA2 sum [closed]

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 8 years ago.
Improve this question
Below is the code which generates MD5 / SHA2 sum of individual files present under directory or sub directories recursively.
#!/usr/bin/perl -w
use strict;
use warnings;
use File::Find;
use IO::File;
use Digest::MD5;
use Digest::SHA qw(sha256_hex);
find({ wanted => \&process_file, no_chdir => 1 }, #ARGV);
sub process_file {
#my $md5 = Digest::MD5->new;
my $sha2 = Digest::SHA->new(256);
if (-f $_) {
#print "This is a file: $_\n";
open(FILE, $_) or die "Can not open $_";
binmode(FILE);
#my $md5sum = $md5->addfile(*FILE)->hexdigest;
my $sha2sum = $sha2->addfile(*FILE)->hexdigest;
#print sha256_hex(*FILE), " $_\n";
close FILE;
print "$sha2sum $_\n";
}
}
The output of above code is given below.
~$ perl list.pl src
f21e1caa364eaad195d968d28187d5cf1a58c0b7b1f21a8ebcb9ca2539dde175 src/test1.pl
4b3277ec41ba0ff8ed6f9f2593c42e08c2f4e9b66df0d63de7c91559ff7e86fa src/random.py
076231fcbe5887a163278b757f99fb05b27163775ec4706cb2365de3be0906ac src/test.pl
8806c9f58fc91b2e1d6453a7af7e4f9f8b94e2d0f67a84a89b35bfbf517399be src/size.pl
5a1b2080ecc53ced45ed3aa13e47118a9ca2f8505b1e89485b6b681d8e1d264c src/test2.py
5f7c1ff9c7b3dd32f75558dd30324ec085c45a0d0c62190b9a96f211cdf216ea src/java/test3.class
3728ee1a86443fffe9eafd84db82ce68c9640a0a984958f579b0da1a74283d7c src/java/test4.wav
d7169ffbb231e93f47d1c54fddf2144b459bba228de48c30b4bc5a4d297be6fb src/java/test5.java
Updated code to support sha256sum generation.
Now I want to generate a combined MD5 / SHA2 sum from these MD5 / SHA2 sums as input.
Digest::MD5 was first released as a Core module with perl v5.7.3 (March 2002) [1]. The oldest version of perl being widely used today is v5.8.8, so any perl you are going to encounter will have this module available.
The oldest version of Digest::MD5 which I could find (v1.99.59-TRIAL from 1998) already has the add and addfile methods. So whatever version of that module you encounter, you will have the add method available.
You can therefore safely rely on that functionality, instead of having to use some ugly and unportable hack like calling a command line tool.
Make sure that you traverse each directory in a specific order so that the checksum is reproducible.
Note that MD5 is an effectively broken algorithm, which shouldn't be used except to interface with legacy systems. The SHA-2 family of hash functions is preferable for most tasks where a fast hash is required.
[1] Use the corelist command line tool from Module::Corelist to query core modules of different perl versions.
Try:
use File::Find 'find';
use Digest::SHA 'sha256_hex';
my #allsums;
sub process_file {
push #allsums, Digest::SHA->new(256)->addfile($_)->hexdigest . " $_" if -f $_;
}
find({ wanted => \&process_file, no_chdir => 1 }, #ARGV);
print sha256_hex(join ':', sort #allsums), "\n";

Filling a hash with parsed input elements [closed]

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 would like to take a given input, say , and run specific parsings over it and fill a hash with the outputs of those parsings. For example, I'd like this input:
"barcodedSamples": "{\"I-735\":{\"barcodes\":[\"IonXpress_001\"]},\"13055\":{\"barcodes\":[\"IonXpress_002\"]}}",
to be parsed (using a combination of grep and some more specific fiddling that I don't have a strong grasp on) into a table that lists the barcodes and sample names as follows:
barcode sample
IonXpress_001 I-735
IonXpress_002 13055
where "barcode" and "sample" are treated as keys. Another example is that I would like to grep to a line that starts:
"library": "hg19",
and map the value "hg19" (so, the string inside the second set of quotation marks, programmatically speaking) to an arbitrary key like "lib":
Library
hg19
The string closely resembles JSON, however requires some cleaning up to become valid JSON.
#!/usr/bin/perl
use strict;
use warnings FATAL => qw/all/;
use JSON;
use Data::Dumper;
my $json_string = '"barcodedSamples": "{\"I-735\":{\"barcodes\":[\"IonXpress_001\"]},\"13055\":{\"barcodes\":[\"IonXpress_002\"]}}"';
$json_string =~ s/\\//g; # remove escape backslashes.
$json_string =~ s/"\{/{/; # remove an invalid opening quote.
chop $json_string; # remove an invalid closing quote.
$json_string = '{' . $json_string . '}'; # wrap in curly braces.
my $json_object = JSON->new( );
my $perl_ref = $json_object->decode( $json_string );
print Dumper( $perl_ref );
That string you're parsing looks suspiciously like JSON. Why not just use the JSON module (which comes with newer Perls, but can be installed from CPAN for older ones) instead of writing your own parser?

How to remove a $ character from a variable's value in Perl? [closed]

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
Suppose I have a variable which is assigned some string containing $ character. For example:
$a="$192.168.1.1";
I have to remove the $ character using Perl. The text is assigned to the variable implicitly.
How to do it?
$v =~ s/\$//; # this does not work for me :(
$="$192.168.1.1"
$ips =~ substr$ips ,1);
push (#planets, $ips
Firstly, note that you can't use double quotes to assign to $a like that, since $192 will be interpolated and will almost certainly fail.
You should always use use strict; and use warnings; in any Perl code. It would have produced a warning if you actually did attempt that assignment.
So, if your assignment is explicit, use single quotes instead:
my $a = '$192.168.1.1';
Then, if the $ is always there, just use substr - it'll be much faster than using a regular expression.
$a = substr($a, 1);
If you don't know for certain that the $ will be there, then the line you used above does work, if you apply it to the correct variable:
$a =~ s/\$//;
or alternatively:
$a =~ tr/$//d;
Here is semi-working and working code.
Semi-working
$ cat x1.pl | so
#!/usr/bin/env perl
use strict;
use warnings;
my $a = "$192.168.1.1";
print "$a\n";
$a =~ s/\$//;
print "$a\n";
$ perl x1.pl | so
Use of uninitialized value $192 in concatenation (.) or string at x1.pl line 5.
.168.1.1
.168.1.1
$
Working
$ cat x2.pl | so
#!/usr/bin/env perl
use strict;
use warnings;
my $a = '$192.168.1.1';
print "$a\n";
$a =~ s/\$//;
print "$a\n";
$ perl x2.pl | so
$192.168.1.1
192.168.1.1
$
Always use use strict; and use warnings; while you're learning Perl (the first twenty or so years are the hardest).
If your code is not working still, you need to show the equivalent SSCCE (Short, Self-Contained, Correct Example) code and the example output, but it should most definitely include use strict; and use warnings;.