On Sat, Dec 17, 2011 at 08:22:31AM +0000, vishnu.kuma...@wipro.com wrote:
> Hi,

Hello:

> I am trying to convert the string abc.def.ghi.amm to
> abcdefghiamm using split and concatenation. I am missing
> something somewhere.. please help me to fix the code
> 
> my $string = "abc.def.ghi.amm";
> 
> my @d = split(/\./,"$string");
> my $e = @d;
> for (my $i=0; $i < $e; $i++) {
>     print("Value of array element $i is $d[$i]\n"); }
> 
> #concatenation
> for (my $i=0; $i < $e; $i++) {
>       my $abc .= "$d[$i]";
> }
> 
> print("Value after concatenation is $abc\n");
> 
> 
> Output I am getting is Value after concatenation is "amm"

Make sure you always use the 'strict' and 'warnings' pragmas.
They should usually be the first couple of lines in every Perl
script or module file you write (i.e., right after your shebang).

use strict;
use warnings;

It looks like $abc in the file scope is not declared, and $abc
within the for-loop is only visible within that loop. That
explains your erroneous results. The 'strict' pragma would have
made it an error to refer to $abc without declaring it.

For example, executing your program with the strict and warnings
pragmas yields the following output:

Global symbol "$abc" requires explicit package name at - line 13.
Execution of - aborted due to compilation errors.

(Line 13 being your last line with the print statement on it)

See how Perl detects the problem for you and refuses to execute
until you fix it? Never write Perl code without these pragmas. :)
They will save you a lot of trouble.

That said, as somebody else pointed out, $abc would be undef in
your print statement (if allowed to execute i.e., without the
strict 'vars' pragma enabled) so your alleged output doesn't make
sense given what you have shown us.

The others have already shown you better ways to do this so I
guess I won't repeat them.

> Please do not print this email unless it is absolutely
> necessary. 

/me prints this E-mail unnecessarily. >:)

Regards,


-- 
Brandon McCaig <bamcc...@gmail.com> <bamcc...@castopulence.org>
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bamccaig.com/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'

Attachment: signature.asc
Description: Digital signature

Reply via email to