What is the right way of concatenating strings
cool
created: 2006-05-01 14:07:36
#!/usr/bin/perl -w
...... 
......
.....
$input="$input"."$temp";
If I don't use double corse "" for the concatinating strings.. and use -w (warining) it gives some kind of concatination error. But sometimes even without double corse it works. Pls tell me what is this kind of error and what is the best way to add strings..

2006-05-02 Retitled by [GrandFather] to aid searching (fixed spelling)
Original title: 'What is the right way of concatinating strings'

Re: What is the right way of concatenating strings
created: 2006-05-01 14:11:31
What exactly does the error/warning message say? My blind guess is that it says something about an uninitialized value, meaning that $input and/or $temp is undef.

Are you doing use strict; ?

People commonly do one of these:
$input = $input . $temp;

$input = "$input$temp";
Re^2: What is the right way of concatenating strings
created: 2006-05-02 04:58:14
Your guess is right, its the same err msg. no i am not using strict.
Re: What is the right way of concatenating strings
created: 2006-05-01 14:24:54
$input .= $temp;
Your description of "some kind of concatination[sic] error" requires that I cite [http://jwenet.net/notebook/2005/1036.html|MJD response] #11906:
Look at the error message! Look at the error message!

Caution: Contents may have been coded under pressure.
Re: What is the right way of concatenating strings
created: 2006-05-01 15:30:03

Sometimes, using our imense psychic powers, we can tell what the error message is without being told, but sometimes we get it wrong. You are best to just tell us. Copy and Paste is your friend. It is also good practise to include a sample script the reproduces the problem. Yours does not. I can't run your sample code and see the error. The following code does show warning and most likely it is the one that you see:

use strict;
use warnings;

my $input;
my $temp = 'more stuff';

print $input.$temp."\n";

This shows the warning Use of uninitialized value in concatenation (.) or string.

None if this is pertinent to your question title however. What you are really asking is Is it better to interpolate variables into a string or concatenate them. There is no one answer and at the end of the day do what you can read best (Perl changes it all around internally anyway). However, you never need to do both so $input="$input"."$temp"; is bogus. That can better be written as $input = $input . $temp;, or even better as $input .= $temp;.



DWIM is Perl's answer to Gödel
Re^2: What is the right way of concatenating strings
created: 2006-05-02 04:56:00
mind blowing!! I didnt explain the problem in detail but you got it almost right hats off to you. I admit my mistake. Actully I failed to reproduced the error as I made some changes in my code and it started working. Here is my tiny code:
#!/usr/bin/perl -w
print"Pls enter the file name\n";
my $in=;

open(AA,"$in");
my $input='';
while()
{
  my $temp='';
     $temp=$_;
   $input=$input.$temp;
}
close(AA);
open(BB,">out.txt");
print BB $input;
close(BB);

For my work I need read files and generate it in desired format, so I rely mostly on concatination as above. and error that is produced same as u stated. Pls tell me also what all mistakes I have done in this small piece of code.
Re^3: What is the right way of concatenating strings
created: 2006-05-02 07:24:58

There are not really gaping errors, but there are a few things that could be cleaned up in various ways.

You use -w in the shebang line which enables warnings, but you should add a use strict; line too.

It is strongly recommended that you use a three parameter open, especially when you obtain the name of the file from the user (as in this case).

You have a redundant assignment to $temp. The declaration for temp can be moved into the conditional expression for the while loop or omited all together. However that impinges somewhat on another decision - should you output in the input loop, or should you slurp (at present you are slurping).

A better way to slurp is:

my $input = do {local $/; ;};

That replaces your whole while loop by setting the input line seperator to null and reading everything into $input in one big slurp (you begin to see where the name comes from perhaps). That is ok for small files, but gets to be a problem if the file is large. For large files it is much better to process the file a line at a time like this:

#!/usr/bin/perl -w
use strict;

print "Please enter the file name\n";
my $in = ;

open inFile, '<', $in;
open outFile, '>', 'out.txt';

while () {
    my $line = $_;
    # ... do stuff to $line here
    print outFile $line;
}

close inFile;
close outFile;

That way only one line of data is in memory at a time so memory usage remains low. The down side is that if you need to manipulate multiple lines as a unit things can get messy. When you bump up against that situation come back and we will help again, or [Super Search] for 'multiple lines' and read through some of the past questions that are relevant.

Update: s|%/|$/|g


DWIM is Perl's answer to Gödel
Re^4: What is the right way of concatenating strings
created: 2006-05-02 09:20:33
yummmi, I really like that slurping concept. Just one line code..perl is amazing, Thanx again man. Can you pl explain me what do mean by three parameter here->> " It is strongly recommended that you use a three parameter open, especially when you obtain the name of the file from the user (as in this case) " and also throgh some light on things (how this is working)inside the curlies on right hand side...please
my $input = do {local %/; ;};
waiting...
Re^5: What is the right way of concatenating strings
created: 2006-05-02 09:53:55

Many functions in Perl can be called with a variable number of arguments. For example, [doc://split]:

split /PATTERN/,EXPR,LIMIT
split /PATTERN/,EXPR
split /PATTERN/

In this case, Perl will assume some default values for the arguments you don't specify. In the case of [doc://open], you can do:

open FILEHANDLE,EXPR
open FILEHANDLE,MODE,EXPR
open FILEHANDLE,MODE,EXPR,LIST
open FILEHANDLE,MODE,REFERENCE
open FILEHANDLE

As you can see, there's more than one way to do it :^). You're being advised to use the three argument form of open, which normally reads like this:

open $fd, '<', 'input_file' or die "open: $!"; ## <-- you should always check for errors.
my $input = do {local %/; ;};

As for this, first take a look to Coping with scoping to understand what local means.

--
David Serrano

Re^5: What is the right way of concatenating strings
created: 2006-05-02 16:25:11

Open comes in a number of flavours. The two parameter open combines the open mode and file name in the second parameter. The three parameter open seperates the mode (second parameter) from the file name (third parameter). If you use the two parameter open and especially if you don't specify the mode because you want input, a user supplied file name that starts with '<', '>' or any of the other mode characters will set the file mode. That can include doing some pretty interesting stuff like forking a child process!

Now for that Perl magic:

my $input = do {local $/; ;};

The do lets you put a block of statements where an expression is allowed. The result of the do block is the result of the last statement evaluated.

The special variable $/ stores the input line seperator. By default this is whatever line end sequence is native on your system. By declaring it local we save the old value it had and set the value to undef. With $/ set to undef the reads the whole file - there is no line end seperator to match. is the last statement evaluated in the do block so its result is assigned to $input.

Remember though that this reads the whole file in to memory. If the file is small (say up to a few megs) that is no big deal. If the file is gigabytes in size then it can be a real problem. It's a neat thing to know about and use, but you have to suit it to the application.

Update: s|%/|$/|g


DWIM is Perl's answer to Gödel
Re^4: What is the right way of concatenating strings
created: 2006-05-02 17:50:39

my $input = do { local $/; };
uses twice as much memory as
my $input; { local $/; $input = ; }
but the files I use are usually to small to cause me to care.

Supporting evidence

Re^5: What is the right way of concatenating strings
created: 2006-05-02 18:01:32

Thanks for that. I considered saying that the first version used memory proportional to twice the file size, but I wasn't sure. In any case it is transient and, as you say, for small files it doesn't matter.


DWIM is Perl's answer to Gödel
Re^4: What is the right way of concatenating strings
created: 2006-05-04 06:47:37
Just one thing, I forgot to add chomp in the 5th line of my code...
#!/usr/bin/perl -w
use strict;

print "Please enter the file name\n";
my $in = ;
chomp($in);
open inFile, '<', $in;
open outFile, '>', 'out.txt';

while () {
    my $line = $_;
    # ... do stuff to $line here
    print outFile $line;
}

close inFile;
close outFile;
Re: What is the right way of concatenating strings
created: 2006-05-02 19:00:47

Just playing around....more then one way to skin a cat...of course some are preferred over others:

my $input = 'hello';
my $temp  = 'world';
$input = "$input $temp";
my $input = 'hello';
my $temp  = 'world';
$input = $input . ' ' . $temp;
my $input = 'hello';
my $temp  = 'world';
$input .= ' ' . $temp;
my $input = 'hello';
my $temp  = 'world';
$input = join(' ', $input,$temp);
my $input = 'hello';
my $temp  = 'world';
my @temp  = split('', $input);
push @temp, ' ';
push @temp, $_ for split('', $temp);
$input = join('',@temp);


___________
Eric Hodges

perlmonks.org content © perlmonks.org and cool, davidrw, eric256, GrandFather, Hue-Bond, ikegami, Roy Johnson

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03