1

I have a data in scalar variable and I want to divide the data into 2 parts based on certain condition. Data is:

50This is my test data;and this line is for testing.

I want this to be stored in 2 separate variables and result should be:

$first = 50
$second = This is my test data;and this line is for testing.

This is what I have tried, but in single expression how to achieve this?

my $first = $1 if ($line =~ /(\d+)This/);
my $second = $2 if ($line =~ /(\d+)(\w+)/)
1

3 Answers 3

4

I think this is slightly simpler than the two solutions you already have.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $data = '50This is my test data;and this line is for testing.';

my ($first, $second) = $data =~ /^(\d+)(.*)/ or die "No pattern match";

say "first:  $first";
say "second: $second";
Sign up to request clarification or add additional context in comments.

3 Comments

Also, the variables should be named more descriptively by the OP.
@TimurShtatland: I agree completely. But as I know nothing about the data, it would be impossible for me to make that change.
@Dave Cross Thank you.
0

Just try this:

my $line = "50This is my test data;and this line is for testing.";

my ($first, $second) = ($line=~m/(\d+)([^\n]*)$/g);

print "$first\t$second\n";

2 Comments

[^\n]* is the same as .* (as long as you're not using /s). And the final $ is unnecessary as regexes are greedy by default.
If they matching regex line by line then we need check !\n - ([^\n]*)$
0

Do this:

(\d+)([\s\S]+)

Number is in the first capturing group, remaining sentence in the second.

Demo

3 Comments

Why [\s\S] instead of just .?
. won't consider \n
If that's important (and I'm not sure it is here) then using /s on the match operator is a better way to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.