Perl Interview Questions and Answers - March 2023 Updated
John","Smith", 9999 9999, "42, some street, some area", "bangalore",560038
in above strings "9999 9999" should be single string and "42, some street, some area" should be single string and 560038 should be single string remaining separate variables write perl program in multiple methods
Sure, here are three different methods to accomplish the task:
Method 1:
use strict; use warnings; my $string = '"John","Smith", 9999 9999, "42, some street, some area", "bangalore",560038'; # Remove quotes from the string and split by comma my @data = map { s/^\s+|\s+$//g; $_ } split /,(?=(?:[^"]*"[^"]*")*[^"]*$)/, $string; # Assign each value to a separate variable my ($first_name, $last_name, $phone_number, $address, $city, $zip_code) = @data; # Output the variables print "First Name: $first_name\n"; print "Last Name: $last_name\n"; print "Phone Number: $phone_number\n"; print "Address: $address\n"; print "City: $city\n"; print "Zip Code: $zip_code\n";
use strict; use warnings; my $input = '"John","Smith", 9999 9999, "42, some street, some area", "bangalore",560038'; my ($first_name, $last_name, $phone_number, $address, $city, $zip_code) = $input =~ /"([^"]+)",\s*"([^"]+)",\s*(\d+\s*\d+),\s*"([^"]+)",\s*"([^"]+)",(\d+)/; print "First Name: $first_name\n"; print "Last Name: $last_name\n"; print "Phone Number: $phone_number\n"; print "Address: $address\n"; print "City: $city\n"; print "Zip Code: $zip_code\n";
my $string = '"John","Smith", 9999 9999, "42, some street, some area", "bangalore",560038"'; my @data = (); my $buffer = ''; my $in_quotes = 0; # Iterate through each character of the string for my $char (split //, $string) { # Check if current character is a comma and not within quotes if ($char eq ',' && !$in_quotes) { # Add the current buffer to the data array push @data, $buffer; # Reset the buffer $buffer = ''; } else { # Add the current character to the buffer $buffer .= $char; # Check if current character is a quote if ($char eq '"') { # Toggle the flag indicating if we're currently within quotes $in_quotes = !$in_quotes; } } } # Add the final buffer to the data array push @data, $buffer; # Remove any leading or trailing whitespace from each data element map { s/^\s+|\s+$//g; $_ } @data; # Assign each value to a separate variable my ($first_name, $last_name, $phone_number, $address, $city, $zip_code) = @data; # Output the variables print "First Name: $first_name\n"; print "Last Name: $last_name\n"; print "Phone Number: $phone_number\n"; print "Address: $address\n"; print "City: $city\n"; print "Zip Code: $zip_code\n";
0 Comments:
Post a Comment
Note: only a member of this blog may post a comment.
<< Home