Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array last element 2

Status
Not open for further replies.

PerlElvir

Technical User
Aug 23, 2005
68


How can I join ($special) to last element in array?

so I have :
---------------------------

@names=(Smith,Elvir,Damir)

and

$special

----------------------


now I have for loop

------------------------

for ( $i = 0; $i <= $#names; ++$i )
{
print $names."\n";
}

------------------------------

so now I want insert in DB like this

Smith
Elvir
Damir.$special


????????????
 
Wow, did you try working this out on your own first? The code you posted isn't going to work at all.

I'm going to assume $special is a variable and not the literal string '$special'. One question though, do you want that period in there or were you just illustrating you wanted to concatenate the string $special?

Either way, if you cleaned up the code you posted, you've answered your own question by using $#names.
Code:
my $special = 'some text';
my @names = qw/Smith Elvir Damir/;

for (my $i = 0; $i <= $#names; $i++) {
    if ($i == $#names) {
        print $names[$i].$special, "\n";
    } else {
        print $names[$i], "\n";
    }
}
Or, if you want to shorten the code for the loop, you could do something like:
Code:
for my $i (0..$#names) {
    print $names[$i] . ($i == $#names ? "$special\n" : "\n");
}
You really don't need to use $i in this example, but I have no way to know if you're using $_ for something else.
 
if it's after the last element in the array, then it's after the entire array:
Code:
print join("\n", @names), $special;
or if you're looking to alter the array:
Code:
$names[-1] .= $special;
print join("\n", @names);

- Andrew
Text::Highlight - A language-neutral syntax highlighting module in Perl
also on SourceForge including demo
 


My code dont work that for sure, I just wanted to let you know that I have loop and..., but "rharsh" you are the man ;)

my $special = 'some text';
my @names = qw/Smith Elvir Damir/;

for (my $i = 0; $i <= $#names; $i++) {
if ($i == $#names) {
print $names[$i].$special, "\n";
} else {
print $names[$i], "\n";
}
}

thats what I need ;)

Thx all
 
Great, I'm glad you got what you needed and thanks for the star.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top