LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl replace backslash (https://www.linuxquestions.org/questions/programming-9/perl-replace-backslash-542650/)

rjcrews 04-02-2007 09:33 AM

Perl replace backslash
 
Hi all,

Any ideas why this code will not open the file and replace the backslashes? Trying to do a .csv import into a DB and the \, is screwing it up if it occurs in the file. I have tried about 10 different ways to remove the \ from the data file.

If this is the correct way to remove backslashes, am I not rewriting the file correctly?

Thanks!

Code:


open UPLOADFILE, ">$upload_dir/$filename";

binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
  print UPLOADFILE;
}

close UPLOADFILE;



open (FILE, "/$upload_dir/$filename");
while(<FILE>){

        $_ =~ s/\\//g;

}
close(FILE);


wjevans_7d1@yahoo.co 04-02-2007 10:46 AM

I think you want instead:

Code:

open UPLOADFILE, ">$upload_dir/$filename";

binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
  $_ =~ s/\\//g;
 
  print UPLOADFILE;
}

close UPLOADFILE;

Different people have different styles of writing Perl code. You seem to prefer extensive use of $_ and avoiding mentioning it explicitly when you do, so maybe you want this equivalent code:

Code:

open UPLOADFILE, ">$upload_dir/$filename";

binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
  s/\\//g;
 
  print UPLOADFILE;
}

close UPLOADFILE;

This code removes the backslashes. But you mentioned replacing them, not removing them. Replacing them with what?

If you indeed do want to replace them with something else, do this:

Code:

open UPLOADFILE, ">$upload_dir/$filename";

binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
  s/\\/somethingelse/g;
 
  print UPLOADFILE;
}

close UPLOADFILE;

Would that something else be a forward slash? If so, don't forget to "escape" it, thus:

Code:

open UPLOADFILE, ">$upload_dir/$filename";

binmode UPLOADFILE;

while ( <$upload_filehandle> )
{
  s/\\/\//g;
 
  print UPLOADFILE;
}

close UPLOADFILE;

Hope this helps.

rjcrews 04-02-2007 12:02 PM

That did help, thanks, I did not realize it was that easy to do the replacement while writing the file.


All times are GMT -5. The time now is 06:52 AM.