Re: search and replace on an array



ebm wrote:

[top-posting corrected. Please don't do that]


David Squire wrote:
David Squire wrote:

Why do you want to do this? Why not just interpolate the directory path
and filename into a string at the time it is needed, e.g.:

for my $Dir ('c:/path/to', 'd:/new/path') { # note you don't need to use
Windows style slashes
for my $File ('File1', 'File2') {
open my $FileHandle, "$Dir/$File", '<' or die "Can't open
$Dir/$File:$!";
Whoops! That should be:
open my $FileHandle, '<', "$Dir/$File" or die "Can't open $Dir/$File:$!";

# ... do stuff
}
}


> Yeah, I know it can be done that way too, but that's not what I'm
> really looking for.
> This is a part of a larger script and I'm not going to rewrite the
> whole this for this.
> do you have any ideas on how to search and replace on an array?
>

Sure. Just use map, as you did in your original post:

----

#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper;

my @files = ('File1','File2');
my $path = ('c:/path/to/');

my @PathFiles = map { $path . $_ } @files; # Why were you making an array ref here?

print Dumper(\@PathFiles);

my $newPath = 'D:/new/place/';

@PathFiles = map { $_ =~ s/^\Q$path\E/$newPath/; $_ } @PathFiles;

print Dumper(\@PathFiles);

----

Output:

$VAR1 = [
'c:/path/to/File1',
'c:/path/to/File2'
];
$VAR1 = [
'D:/new/place/File1',
'D:/new/place/File2'
];



DS
.



Relevant Pages

  • Re: search and replace on an array
    ... David Squire wrote: ... and filename into a string at the time it is needed, ... Windows style slashes ...
    (comp.lang.perl.misc)
  • Fwd: Re: dbm again
    ... The hash has only one key, ... Can't use string ) as an ARRAY ref while strict refs in ... No quotes around the string after die. ...
    (perl.beginners)
  • Re: Fwd: Re: dbm again
    ... The hash has only one key, ... Can't use string ) as an ARRAY ref while strict refs in ... It seems like I am somehow dealing with a reference to an array!? ... as a string and tried to be derefenced. ...
    (perl.beginners)
  • Re: Sort two dimensional array with multiple keys
    ... Can't use string as an ARRAY ref while "strict refs" ... Blind allegiance is the mother of tyranny, not patriotism. ...
    (comp.lang.perl.misc)
  • Problems using Module PDF::Create
    ... the module 'PDF::Create' works fine except the 'Rotate' Option. ... Can't use string as an ARRAY ref while "strict refs" in use at ...
    (comp.lang.perl.misc)