Suvasish Sarker
Suvasish Sarker

Reputation: 435

Character input in a array and accessing by array index

To solve a problem of subsequence check I am trying to take two string input in two different array and access them by array indexs ?

In C i did it like below..

char text[25000],pattern[25000];
scanf("%s %s",text,pattern);

and i can access each character through array index.

How can i do the same in perl??

In perl i haven't found anything specific to access array indexes. All i got is to use the perl split function..

my @pattern = split(" ",<>);

This splits the input based on space and assigns to array indexes, if the input is like canada nad split will assign canada to $pattern[0] and nad to $pattern[1]

but i want them in two separate array?

i found another user of split like..

my @pattern = split(undef,<>);
foreach my $val (@pattern){
     print $val."\n";
}

this can access all the character of the string but the problem is i can't assign them in two different arrays.

Thanks in advance of any idea/suggestion.

Got it, i was looking for something like this..

my ($text,$pattern) = split(' ',<>);
my @textarr= split //,$text;
my @patterarr= split //,$pattern;

Upvotes: 0

Views: 140

Answers (1)

ikegami
ikegami

Reputation: 386396

It's not clear if you want

# Two strings (which are scalars, not arrays)
my $text = "canada";
my $pattern = "nad";

or

# Two array of single-char strings
my @text_chars = ("c", "a", "n", "a", "d", "a");
my @pattern    = ("n", "a", "d");

If you want the former,

my ($text, $pattern) = split(' ', $line);

If you want the the latter, follow up with

my @text_chars    = split //, $text;
my @pattern_chars = split //, $pattern;

The latter can also be achieved using the following if you don't mind dealing with references to arrays:

my ($text_chars, $pattern_chars) = map [ split // ], split ' ', $line;

In the above, $line is produced using

chomp( my $line = <> );

Upvotes: 1

Related Questions