len8200
len8200

Reputation: 85

It is necessary to make several separate variables from a string

How to get three separate variables from a string? my $string = '2019-08-20'; my ($year, $month, $day);

Upvotes: 0

Views: 72

Answers (3)

Dave Cross
Dave Cross

Reputation: 69224

As others have pointed out, you can use split() to do what you ask for. But I wonder if what you're asking for is really the best approach.

I don't know why you want three different variables, but would suggest that when you have a date and you want to access different parts of it, then it's usually a better idea to create an object.

use Time::Piece;

my $date = Time::Piece->strptime('2019-08-20');

You can then get the individual elements that you want;

say $date->year;
say $date->mon;
say $date->mday;

But you can also get other potentially useful things:

say $date->month; # August
say $date->day;   # Tuesday

Or you could use strftime() to reformat the date:

say $date->strftime('%A, %d %B %Y'); # Monday, 20 August 2019

There's a lot more you can do with Time::Piece.

Upvotes: 1

ssr1012
ssr1012

Reputation: 2589

You can use split function to get three values from the input. As mentioned in the comment ikegami

my $str = '2019-08-20';

my ($year, $month, $day) = split /-/, $str;

print "$year\n$month\n$day\n";

Thanks

Upvotes: 0

AnFi
AnFi

Reputation: 10903

my  $string = '2019-08-20';
my ($year, $month, $day) = $string =~ /^(\d{4})-(\d{2})-(\d{2})$/;

if( defined($day) ) {
  print ("$year $month $day\n");
}else{
  print "no match\n";
}

~

Upvotes: 1

Related Questions