I'm new to this (first post!) and have been searching for a similar question for a number of days but cannot for the life of me find something similar enough to help (or cannot recognise it if it is there). If I'm wrong to post this question, please direct me to the right place :)
::
So I've just started using Perl, and I need to take some input:
xxx00_xxxx_xxx00 and split the string into bits separated by the '_'. This I have done using arrays.
problem is now I want to assign the values from the arrays into variables so I can use them.
Here is my novice code:
#!/usr/bin/perl
use strict;
use warnings;
# take input
print "enter ID:\n";
my $input = <>;
#split input
my @values = split( '_', $input );
print "$values[0]\n";
print "$values[1]\n";
print "$values[2]\n";
#assign split components to variables
my $customer_ID = $values[0];
my $service_ID = $values[1];
my $ipac_ID = $values[2];
#print components
print "Customer ID: $customer_ID";
print "Service ID: $service_ID";
print "IPAC ID: $ipac_ID";
exit 0;
BTW I know I have errors on line 19 (I cant figure that out either...)
any help appreciated - thanks!
The message The second parameter of split is a string, not an array is from the Padre IDE you are using, not from Perl. It is produced by Padre's "Beginner's Mode", which naïvely checks whether there is an @ between the text split and the next semicolon, even across multiple lines, and if so then it assumes that you have made a mistake. Of course that approach doesn't allow for comments.
The only errors you have - if you can call them errors - are
You leave the newline in place at the end of your input string, so it will look like "xxx00_xxxx_xxx00\n" and split will produce "xxx00", "xxxx", "xxx00\n". A simple chomp $input will remove that newline
You don't print a newline after each scalar value, so your output is all on one line and your session looks like this
enter ID:
xxx00_xxxx_xxx00
xxx00
xxxx
xxx00
Customer ID: xxx00Service ID: xxxxIPAC ID: xxx00
And all you need to do there is add a newline on each print (like you did with your earlier print statements) like this
print "Customer ID: $customer_ID\n";
print "Service ID: $service_ID\n";
print "IPAC ID: $ipac_ID\n";
A tidier version of your program with more obvious choices would look like this
#!/usr/bin/perl
use strict;
use warnings;
# take input
print 'Enter ID: ';
my $input = <>;
chomp $input;
# Split input
my @values = split /_/, $input;
print "$_\n" for @values;
# Assign split components to variables
my ($customer_ID, $service_ID, $ipac_ID) = @values;
#print components
print "Customer ID: $customer_ID\n";
print "Service ID: $service_ID\n";
print "IPAC ID: $ipac_ID\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With