Replace substring in all values of a hash array?

Discussion in 'Perl Misc' started by Brian McCauley, May 23, 2005.

  1. Abusing package variables like this is bad.
    A regex is just a way of describing a pattern to match. To do a
    substution you need the sustitution operator s/// or you can use substr().


    To apply this to all the values in %flora_and_fauna:

    s/_green\.gif/_yellow.gif/ for values %flora_and_fauna;
    Brian McCauley, May 23, 2005
    1. Advertisements

  2. Brian McCauley

    Anno Siegel Guest

    $flora_and_fauna{$current::page} =~ s/green\.gif/yellow.gif/;
    All values? In your code you are only considering one value at a
    Add the line as indicated.

    If you have a list @pages of all pages, this is more compact than
    your loop:

    s/green\.gif/yellow.gif/ for
    @flora_and_fauna{ grep exists $flora_and_fauna{ $_}, @pages};

    (Code untested)

    Anno Siegel, May 23, 2005
    1. Advertisements

  3. Brian McCauley

    michael Guest

    I would like to replace substrings in hash values, for example:

    %flora_and_fauna =
    ('z0.html' => 'flora_and_fauna_green.gif alt=flora and fauna',
    'z1.html' => 'pretty_flower_green.gif alt=pretty flowers',
    'z2.html' => 'deadly_vines_green.gif alt=deadly vines');

    # the above values being linked images rather than text links

    # sometime later in the script I run an if statement to check
    # if filename is in array for setting relevant CSS html class

    $class::value = "yellow";
    else {
    $class::value = "green";

    Depending on the outcome of above if block, I would like to modify the
    substring "_green.gif" to become "_yellow.gif" in all values of the
    %flora_and_fauna array. How by using regex and replace can this be done?

    michael, May 23, 2005
  4. Brian McCauley

    michael Guest

    Abusing package variables like this is bad.

    I had a guilt feeling about it but wasn't able to figure variable scope in
    time of getting the script functional.
    Thanks for these useful tips.
    And for this, it got all working as needed.

    michael, May 23, 2005
  5. Brian McCauley

    michael Guest

    s/green\.gif/yellow.gif/ for
    Thanks fir this info - will test.

    michael, May 23, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.