2

I'd like to access a real variable with a name equal to a string of characters that I have. Something like this (I'll make the example as clean as possible):

character(len=5) :: some_string
real :: value
value = 100.0
some_string = 'value'

At this point, how do I create an association between the character array value and the name of my real variable, value, so that I can write the value of 100.0 by referring to the string some_string?

francescalus
  • 30,576
  • 16
  • 61
  • 96
Taylor
  • 59
  • 2
  • 5
  • I closed this slightly older question, because this one was not tagged correctly for a long time and the other one got more attention and more good answers. This one had a better title though. Any objections? – Vladimir F Героям слава Dec 09 '17 at 14:53

2 Answers2

2

That's pretty much not going to happen in Fortran. There are no "dynamic" language features like this available in the language. Variable names are a compile-time only thing, and simply don't exist at runtime (the names have been translated to machine addresses by the compiler).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Ugh. THank you for your quick response. I was afraid of this. Why can't everything be like perl... – Taylor Feb 13 '12 at 21:42
  • Any suggestions for proceeding? Commonly used workarounds? – Taylor Feb 13 '12 at 21:43
  • 1
    I would suggest looking carefully at *why* you believe you need to do this, and reformulate your code so you don't need to. There is always a way. – Greg Hewgill Feb 13 '12 at 21:47
1

This is how I work around this:

character(100) :: s
integer        :: val  
val = 100   
write(s,*) val   
print *,trim(s)

This prints 100 to the screen. There is some strangeness which I do not understand however, the character s needs to be very large (100 int his case). For instance, if you use 3 instead of 100, it does not work. This is not a critical thing, as the use of trim fixes this, but it would be nice if somebody could answer why this is the case.

Either way, this should work.

DisplayName
  • 3,093
  • 5
  • 35
  • 42
  • This seems to misinterpret the question. The original question wasn't how to copy the *value* of a variable X to a string variable Y; it was how to refer to a variable X by means of a variable Y that contains X's *name*. – J. D. Oct 07 '21 at 14:22