How to convert string into equation and solve it in Perl? [duplicate] - perl

If one string is expressed like below
$str = "5+2-1";
I'd like to get the calculation result from that string.
How do I convert to scalar to compute this?
Thanks.

The easiest way to do this:
print eval('5+2-1');
but it's not safe:
print eval('print "You are hacked"');
You need to check string before eval it.
Also you can use Math::Expression module or many other modules from cpan:
#!/usr/bin/perl
use strict;
use warnings;
use Math::Expression;
my $env = Math::Expression->new;
my $res = $env->Parse( '5+2-1' );
# my $res = $env->Parse( 'print you are hacked' ); # no math expression here
print $env->Eval( $res );

If you are sure the string does not contain any malicious code you can use eval to treat the content of it as perl code.
#!/usr/bin/perl
use strict;
use warnings;
my $string = "5+2-1";
print eval($string);
#print 6

Related

Pass a hash object from one perl script to another using system

I have the following perl script, that takes in a parameters' file and stores it into a hash. I want to modify & pass this hash to another perl script that I am calling using the system command:
script1.pl
#!/usr/bin/perl -w
# usage perl script1.pl script1.params
# script1.params file looks like this:
# PROJECTNAME=>project_dir
# FASTALIST=>samples_fastq.csv
use Data::Dumper;
my $paramfile = $ARGV[0];
# open parameter file
open PARAM, $paramfile or die print $!;
# save it in a hash
my %param;
while(<PARAM>)
{
chomp;
#r = split('=>');
$param{$r[0]}=$r[1];
}
# define directories
# add to parameters' hash
$param{'INDIR'} = $param{'PROJECTNAME'}.'/input';
$param{'OUTDIR'} = $param{'PROJECTNAME'}.'/output';
.... do something ...
# #samples is a list of sample names
foreach (#samples)
{
# for each sample, pass the hash values & sample name to a separate script
system('perl script2.pl <hash> $_');
}
script2.pl
#!/usr/bin/perl -w
use Data::Dumper;
## usage <script2.pl> <hash> <samplename>
# something like getting and printing the hash
my #string = $ARGV[0];
print #string;
If you can help me showing how to pass and get the hash object (something simple like printing the hash object in the second script would do), then I'd appreciate your help.
Thanks!
What you're looking for is something called serialisation. It's difficult to directly represent a memory structure in such a way as to pass it between processes, because of all sorts of fun things like pointers and buffers.
So you need to turn your hash into something simple enough to hand over in a single go.
Three key options for this in my opinion:
Storable - a perl core module that lets you freeze and thaw a data structure for this sort of purpose.
JSON - a text based representation of a hash-like structure.
XML - bit like JSON, but with slightly different strengths/weaknesses.
Which you should use depends a little on how big your data structure is.
Storable is probably the simplest, but it's not going to be particularly portable.
There's also Data::Dumper that's an option too, as it prints data structures. Generally though, I'd suggest that has all the downsides of all the above - you still need to parse it like JSON/XML but it's also not portable.
Example using Storable:
use strict;
use warnings;
use Storable qw ( freeze );
use MIME::Base64;
my %test_hash = (
"fish" => "paste",
"apples" => "pears"
);
my $frozen = encode_base64 freeze( \%test_hash );
system( "perl", "some_other_script.pl", $frozen );
Calling:
use strict;
use warnings;
use Storable qw ( thaw );
use Data::Dumper;
use MIME::Base64;
my ($imported_scalar) = #ARGV;
print $imported_scalar;
my $thing = thaw (decode_base64 $imported_scalar ) ;
print Dumper $thing;
Or:
my %param = %{ thaw (decode_base64 $imported_scalar ) };
print Dumper \%param;
This will print:
BAoIMTIzNDU2NzgEBAQIAwIAAAAKBXBhc3RlBAAAAGZpc2gKBXBlYXJzBgAAAGFwcGxlcw==
$VAR1 = {
'apples' => 'pears',
'fish' => 'paste'
};
Doing the same with JSON - which has the advantage of being passed as plain text, and in a general purpose format. (Most languages can parse JSON):
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
my %test_hash = (
"fish" => "paste",
"apples" => "pears"
);
my $json_text = encode_json ( \%test_hash );
print "Encoded: ",$json_text,"\n";
system( "perl", "some_other_script.pl", quotemeta $json_text );
Calling:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
use Data::Dumper;
my ($imported_scalar) = #ARGV;
$imported_scalar =~ s,\\,,g;
print "Got: ",$imported_scalar,"\n";
my $thing = decode_json $imported_scalar ;
print Dumper $thing;
Need the quotemeta and the removal of slashes unfortunately, because the shell interpolates them. This is the common problem if you're trying to do this sort of thing.

Passing hash reference as an argument to perl script from perl script

I want to pass a hash reference as an argument from one perl script (script1.pl) to another perl script (script2.pl). This is how my code looks:
----------------------------script1.pl---------------------------------
#!/usr/bin/perl -w
use strict;
use warnings;
my %hash = (
'a' => "Harsha",
'b' => "Manager"
);
my $ref = \%hash;
system "perl script2.pl $ref";
----------------------------script2.pl---------------------------------
#!/usr/bin/perl -w
use strict;
use warnings;
my %hash = %{$ARGV[0]};
my $string = "a";
if (exists($hash{$string})){
print "$string = $hash{$string}\n";
}
And this is the output error:
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `perl script2.pl HASH(0x8fbed0)'
I can't figure out the right way to pass the reference.
A hash is an in memory data structure. Processes 'own' their own memory space, and other processes can't just access it. If you think about it, I'm sure you'll spot why quite quickly.
A hash reference is an address of that memory location. Even if the other process could 'understand' it, it still wouldn't be able to access the memory space.
What we're talking about here is actually quite a big concept - Inter Process Communication or IPC - so much so there's a whole chapter of the documentation about it, called perlipc.
The long and short of it is this - you can't do what you're trying to do. Sharing memory between processes is much more difficult than you imagine.
What you can do is transfer the data back and forth - not by reference, but the actual information contained.
I would suggest that for your example, the tool for the job is JSON, because then you can encode and decode your hash:
#!/usr/bin/perl -w
use strict;
use warnings;
use JSON;
my %hash = (
'a' => "Harsha",
'b' => "Manager"
);
my $json_string = to_json( \%hash );
print $json_string;
This gives:
{"b":"Manager","a":"Harsha"}
Then your can 'pass' your $json_string - either on the command line, although bear in mind that any spaces in it confuses #ARGV a bit if you're not careful - or via STDIN.
And then decode in your sub process:
use strict;
use warnings;
use JSON;
my $json_string = '{"b":"Manager","a":"Harsha"}';
my $json = from_json ( $json_string );
my $string = "a";
if (exists($json -> {$string} )){
print "$string = ",$json -> {$string},"\n";
}
(You can make it more similar to your code by doing:
my $json = from_json ( $json_string );
my %hash = %$json;
Other options would be:
use Storable - either freezing and thawing ( memory) or storing and retrieving (disk)
use IPC::Open2 and send data on STDIN.
There's a variety of options really - have a look at perlipc. But it's not as simple a matter as 'just passing a reference' unfortunately.
Use Storable to store data in first script and retrieve it from other.
firstscript.pl
store (\%hash, "/home/chankey/secondscript.$$") or die "could not store";
system("perl", "secondscript.pl", $$) == 0 or die "error";
secondscript.pl
my $parentpid = shift;
my $ref = retrieve("/home/chankey/secondscript.$parentpid") or die "couldn't retrieve";
print Dumper $ref;
You've received the %hash in $ref. Now use it the way you want.
You can't pass a reference from one script to another - that reference only has meaning within the currently running instance of perl.
You would need to "serialise" the data in the first script, and then "deserialise" it in the second.
Your way of calling perl file is wrong.
Just change the way of calling it and you are done.
Script1.pl
---------------------------------
#!/usr/bin/perl -w
use strict;
use warnings;
my %hash = (
'a' => "Harsha",
'b' => "Manager"
);
system("perl","script2.pl",%hash);
Use this %hash in another perl script as shown below.
Script2.pl
----------------------------------
#!/usr/bin/perl -w
use strict;
use warnings;
my %hash = #ARGV;
my $string = "a";
if (exists($hash{$string})){
print "$string = $hash{$string}\n";
}
OutPut is
a = Harsha

get all possible permutations of words in string using perl script

I have a string like this , how are you , I want to get all possible shuffle of word like
how are you
are how you
you how are
you are how
are you how
how you are
How can I make it in perl script , i've tried the shuffle function but it returns only one string of shuffle .
If you are not familiar with Perl script, you can tell me the logic only.
Note: The words count in string are not constant.
What you're talking about are permutations. This can be done in Perl with the Algorithm::Permute module:
If you've installed the module, here's a shell one-liner that will do it for you:
perl -e'
use Algorithm::Permute qw();
my $str = $ARGV[0];
my #arr = split(/\s+/,$str);
my $ap = new Algorithm::Permute(\#arr);
while (my #res = $ap->next()) { print("#res\n"); }
' 'how are you';
## you are how
## are you how
## are how you
## you how are
## how you are
## how are you
You can use List::Permutor CPAN module:
use strict;
use warnings;
use List::Permutor;
my $perm = new List::Permutor qw/ how are you /;
while (my #set = $perm->next)
{
print "#set\n";
}
Output:
how are you
how you are
are how you
are you how
you how are
you are how
As bgoldst suggested Algorithm::Permute, for faster execution you can write this without using while loop:
use Algorithm::Permute;
my #array = qw(how are you);
Algorithm::Permute::permute {
print "#array\n";
}#array;

Multiplying floats and ints in perl through an if statement

My goal is to utilize perl to multiply a float and an int, I have got this far and am still researching, many thanks to any help.
#!/usr/bin/perl
$float1 = 0.90
print "give me an integer";
$that_integer = <>;
if ($that_integer<=5000) {
print "$that_integer * $float1";
}
Welcome to Perl. A few tips:
Always include use strict; and use warnings; at the top of EVERY Perl script.
chomp your input from <STDIN> to remove the newline at the end.
You can't interpolate expressions. However, you can easily include them in a string easily using printf.
As demonstrated:
#!/usr/bin/perl
use strict;
use warnings;
my $float1 = 0.90;
print "give me an integer: ";
chomp( my $that_integer = <> );
if ( $that_integer <= 5000 ) {
printf "%f\n", $that_integer * $float1;
}
Arbitrary expressions can't be interpolated into double-quotes. Try:
print $that_integer * $float1, "\n";
The perlop documentation page includes all the gory details of parsing quoted constructs.

how to put a field-separator in Spreadsheet::ParseExcel::Simple

The following code works well for me, but I am not able to figure out how to separate columns with a field-separator like comma (,) character.
Please advise, thanks.
#! /usr/bin/perl
use strict;
use warnings;
use Spreadsheet::ParseExcel::Simple;
my #data;
my $xls = Spreadsheet::ParseExcel::Simple->read('mylargefile.xls');
foreach my $sheet ($xls->sheets) {
while ($sheet->has_data) {
#data = $sheet->next_row;
print "#data \n";
}
}
Since #data is an array of cells, you can use the built-in join() function like so:
print join(',', #data);
Or replace the comma with a separator of your choice.