Reputation: 45
I'm trying to write a perl program:
print "Enter the filename:";
$filename = readline STDIN;
print "Enter the string to be compared";
$string1 = readline STDIN;
To combine these two inputs in one go, I did the following:
print "Enter the filename and string to be compared:";
my $input1 = readline STDIN;
my @name = split(' ',$input1); //split the input parameters by space
$filename = $name[0];
$string1 = $name[1];
chomp $string1;
This is functional code,I wanted to know if there is any other way to implement more optimized version for this logic?
Thanks, DD
Upvotes: 2
Views: 853
Reputation: 302
Try using the code bellow with the `comand:perl your_script.pl -file_name 'some_file' -string 'some_string'
use Getopt::Long;
my ( $file_name, $string );
GetOptions(
'file_name=s' => \$file_name,
'string=s' => \$string,
) or die "Could not parse options";
if($file_name eq $string )
{
print "The file name is the same as the string\n";
}else{
print "Not a match\n";
}
Upvotes: 0
Reputation: 5927
What about kite From perl secret
use warnings;
use strict;
print "Enter the filename and string to be compared:";
chomp( my @ar = (~~<>, ~~<> ) );
print @ar;
Upvotes: 2
Reputation: 53478
That's about as optimised as you get. Don't bother trying to hand optimise code until you're sure you need to. Given this is a wait for IO, it will just not matter, because IO is slower than anything you're doing in code.
But if you meant more concise:
print "Enter the filename and string to be compared:";
chomp ( my ( $filename, $string ) = split ' ', <> );
This takes <>
- which is the magic filehandle, and reads either STDIN or a filename specified on command line. (Works like grep
/sed
/awk
).
We split it on a space, in a scalar context - and then hand the values from split to a list assignment to $filename
and $string
. Which is then chomped to strip linefeeds.
Upvotes: 5