0

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;
1
  • You probably don't need them to be in an array. You can use substr to access a single character in a string perl -E'my $text = "text"; say substr($text,2,1)' (prints x) Commented May 17, 2013 at 16:05

1 Answer 1

1

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 = <> );
Sign up to request clarification or add additional context in comments.

3 Comments

I want the later one and the solution works but have a little issue :) I tested it like below.. my $text=<>; my @text_arr=split(//,$text); print @text_arr."\n"; foreach my $val (@text_arr){ print $val."\n"; } It count the newline and the end.How to avoid that?
you can chomp each $text line first to remove the new line character before you split
Updated to handle newline.

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.